1 /*
   2  * Copyright (c) 1997, 2019, 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 "jni.h"
  28 #include "jvm.h"
  29 #include "ci/ciReplay.hpp"
  30 #include "classfile/altHashing.hpp"
  31 #include "classfile/classFileStream.hpp"
  32 #include "classfile/classLoader.hpp"
  33 #include "classfile/javaClasses.hpp"
  34 #include "classfile/javaClasses.inline.hpp"
  35 #include "classfile/modules.hpp"
  36 #include "classfile/symbolTable.hpp"
  37 #include "classfile/systemDictionary.hpp"
  38 #include "classfile/vmSymbols.hpp"
  39 #include "gc/shared/gcLocker.inline.hpp"
  40 #include "interpreter/linkResolver.hpp"
  41 #include "jfr/jfrEvents.hpp"
  42 #include "jfr/support/jfrThreadId.hpp"
  43 #include "logging/log.hpp"
  44 #include "memory/allocation.hpp"
  45 #include "memory/allocation.inline.hpp"
  46 #include "memory/oopFactory.hpp"
  47 #include "memory/resourceArea.hpp"
  48 #include "memory/universe.hpp"
  49 #include "oops/access.inline.hpp"
  50 #include "oops/arrayOop.inline.hpp"
  51 #include "oops/instanceKlass.hpp"
  52 #include "oops/instanceOop.hpp"
  53 #include "oops/markWord.hpp"
  54 #include "oops/method.hpp"
  55 #include "oops/objArrayKlass.hpp"
  56 #include "oops/objArrayOop.inline.hpp"
  57 #include "oops/oop.inline.hpp"
  58 #include "oops/symbol.hpp"
  59 #include "oops/typeArrayKlass.hpp"
  60 #include "oops/typeArrayOop.inline.hpp"
  61 #include "oops/valueArrayOop.inline.hpp"
  62 #include "oops/valueKlass.inline.hpp"
  63 #include "prims/jniCheck.hpp"
  64 #include "prims/jniExport.hpp"
  65 #include "prims/jniFastGetField.hpp"
  66 #include "prims/jvm_misc.hpp"
  67 #include "prims/jvmtiExport.hpp"
  68 #include "prims/jvmtiThreadState.hpp"
  69 #include "runtime/atomic.hpp"
  70 #include "runtime/fieldDescriptor.inline.hpp"
  71 #include "runtime/handles.inline.hpp"
  72 #include "runtime/interfaceSupport.inline.hpp"
  73 #include "runtime/java.hpp"
  74 #include "runtime/javaCalls.hpp"
  75 #include "runtime/jfieldIDWorkaround.hpp"
  76 #include "runtime/jniHandles.inline.hpp"
  77 #include "runtime/orderAccess.hpp"
  78 #include "runtime/reflection.hpp"
  79 #include "runtime/safepointVerifiers.hpp"
  80 #include "runtime/sharedRuntime.hpp"
  81 #include "runtime/signature.hpp"
  82 #include "runtime/thread.inline.hpp"
  83 #include "runtime/vmOperations.hpp"
  84 #include "services/memTracker.hpp"
  85 #include "services/runtimeService.hpp"
  86 #include "utilities/defaultStream.hpp"
  87 #include "utilities/dtrace.hpp"
  88 #include "utilities/events.hpp"
  89 #include "utilities/histogram.hpp"
  90 #include "utilities/macros.hpp"
  91 #include "utilities/vmError.hpp"
  92 #if INCLUDE_JVMCI
  93 #include "jvmci/jvmciCompiler.hpp"
  94 #endif
  95 
  96 static jint CurrentVersion = JNI_VERSION_10;
  97 
  98 #ifdef _WIN32
  99 extern LONG WINAPI topLevelExceptionFilter(_EXCEPTION_POINTERS* );
 100 #endif
 101 
 102 // The DT_RETURN_MARK macros create a scoped object to fire the dtrace
 103 // '-return' probe regardless of the return path is taken out of the function.
 104 // Methods that have multiple return paths use this to avoid having to
 105 // instrument each return path.  Methods that use CHECK or THROW must use this
 106 // since those macros can cause an immedate uninstrumented return.
 107 //
 108 // In order to get the return value, a reference to the variable containing
 109 // the return value must be passed to the contructor of the object, and
 110 // the return value must be set before return (since the mark object has
 111 // a reference to it).
 112 //
 113 // Example:
 114 // DT_RETURN_MARK_DECL(SomeFunc, int);
 115 // JNI_ENTRY(int, SomeFunc, ...)
 116 //   int return_value = 0;
 117 //   DT_RETURN_MARK(SomeFunc, int, (const int&)return_value);
 118 //   foo(CHECK_0)
 119 //   return_value = 5;
 120 //   return return_value;
 121 // JNI_END
 122 #define DT_RETURN_MARK_DECL(name, type, probe)                             \
 123   DTRACE_ONLY(                                                             \
 124     class DTraceReturnProbeMark_##name {                                   \
 125      public:                                                               \
 126       const type& _ret_ref;                                                \
 127       DTraceReturnProbeMark_##name(const type& v) : _ret_ref(v) {}         \
 128       ~DTraceReturnProbeMark_##name() {                                    \
 129         probe;                                                             \
 130       }                                                                    \
 131     }                                                                      \
 132   )
 133 // Void functions are simpler since there's no return value
 134 #define DT_VOID_RETURN_MARK_DECL(name, probe)                              \
 135   DTRACE_ONLY(                                                             \
 136     class DTraceReturnProbeMark_##name {                                   \
 137      public:                                                               \
 138       ~DTraceReturnProbeMark_##name() {                                    \
 139         probe;                                                             \
 140       }                                                                    \
 141     }                                                                      \
 142   )
 143 
 144 // Place these macros in the function to mark the return.  Non-void
 145 // functions need the type and address of the return value.
 146 #define DT_RETURN_MARK(name, type, ref) \
 147   DTRACE_ONLY( DTraceReturnProbeMark_##name dtrace_return_mark(ref) )
 148 #define DT_VOID_RETURN_MARK(name) \
 149   DTRACE_ONLY( DTraceReturnProbeMark_##name dtrace_return_mark )
 150 
 151 
 152 // Use these to select distinct code for floating-point vs. non-floating point
 153 // situations.  Used from within common macros where we need slightly
 154 // different behavior for Float/Double
 155 #define FP_SELECT_Boolean(intcode, fpcode) intcode
 156 #define FP_SELECT_Byte(intcode, fpcode)    intcode
 157 #define FP_SELECT_Char(intcode, fpcode)    intcode
 158 #define FP_SELECT_Short(intcode, fpcode)   intcode
 159 #define FP_SELECT_Object(intcode, fpcode)  intcode
 160 #define FP_SELECT_Int(intcode, fpcode)     intcode
 161 #define FP_SELECT_Long(intcode, fpcode)    intcode
 162 #define FP_SELECT_Float(intcode, fpcode)   fpcode
 163 #define FP_SELECT_Double(intcode, fpcode)  fpcode
 164 #define FP_SELECT(TypeName, intcode, fpcode) \
 165   FP_SELECT_##TypeName(intcode, fpcode)
 166 
 167 // Choose DT_RETURN_MARK macros  based on the type: float/double -> void
 168 // (dtrace doesn't do FP yet)
 169 #define DT_RETURN_MARK_DECL_FOR(TypeName, name, type, probe)    \
 170   FP_SELECT(TypeName, \
 171     DT_RETURN_MARK_DECL(name, type, probe), DT_VOID_RETURN_MARK_DECL(name, probe) )
 172 #define DT_RETURN_MARK_FOR(TypeName, name, type, ref) \
 173   FP_SELECT(TypeName, \
 174     DT_RETURN_MARK(name, type, ref), DT_VOID_RETURN_MARK(name) )
 175 
 176 
 177 // out-of-line helpers for class jfieldIDWorkaround:
 178 
 179 bool jfieldIDWorkaround::is_valid_jfieldID(Klass* k, jfieldID id) {
 180   if (jfieldIDWorkaround::is_instance_jfieldID(k, id)) {
 181     uintptr_t as_uint = (uintptr_t) id;
 182     intptr_t offset = raw_instance_offset(id);
 183     if (is_checked_jfieldID(id)) {
 184       if (!klass_hash_ok(k, id)) {
 185         return false;
 186       }
 187     }
 188     return InstanceKlass::cast(k)->contains_field_offset(offset);
 189   } else {
 190     JNIid* result = (JNIid*) id;
 191 #ifdef ASSERT
 192     return result != NULL && result->is_static_field_id();
 193 #else
 194     return result != NULL;
 195 #endif
 196   }
 197 }
 198 
 199 
 200 intptr_t jfieldIDWorkaround::encode_klass_hash(Klass* k, intptr_t offset) {
 201   if (offset <= small_offset_mask) {
 202     Klass* field_klass = k;
 203     Klass* super_klass = field_klass->super();
 204     // With compressed oops the most super class with nonstatic fields would
 205     // be the owner of fields embedded in the header.
 206     while (InstanceKlass::cast(super_klass)->has_nonstatic_fields() &&
 207            InstanceKlass::cast(super_klass)->contains_field_offset(offset)) {
 208       field_klass = super_klass;   // super contains the field also
 209       super_klass = field_klass->super();
 210     }
 211     debug_only(NoSafepointVerifier nosafepoint;)
 212     uintptr_t klass_hash = field_klass->identity_hash();
 213     return ((klass_hash & klass_mask) << klass_shift) | checked_mask_in_place;
 214   } else {
 215 #if 0
 216     #ifndef PRODUCT
 217     {
 218       ResourceMark rm;
 219       warning("VerifyJNIFields: long offset %d in %s", offset, k->external_name());
 220     }
 221     #endif
 222 #endif
 223     return 0;
 224   }
 225 }
 226 
 227 bool jfieldIDWorkaround::klass_hash_ok(Klass* k, jfieldID id) {
 228   uintptr_t as_uint = (uintptr_t) id;
 229   intptr_t klass_hash = (as_uint >> klass_shift) & klass_mask;
 230   do {
 231     debug_only(NoSafepointVerifier nosafepoint;)
 232     // Could use a non-blocking query for identity_hash here...
 233     if ((k->identity_hash() & klass_mask) == klass_hash)
 234       return true;
 235     k = k->super();
 236   } while (k != NULL);
 237   return false;
 238 }
 239 
 240 void jfieldIDWorkaround::verify_instance_jfieldID(Klass* k, jfieldID id) {
 241   guarantee(jfieldIDWorkaround::is_instance_jfieldID(k, id), "must be an instance field" );
 242   uintptr_t as_uint = (uintptr_t) id;
 243   intptr_t offset = raw_instance_offset(id);
 244   if (VerifyJNIFields) {
 245     if (is_checked_jfieldID(id)) {
 246       guarantee(klass_hash_ok(k, id),
 247     "Bug in native code: jfieldID class must match object");
 248     } else {
 249 #if 0
 250       #ifndef PRODUCT
 251       if (Verbose) {
 252   ResourceMark rm;
 253   warning("VerifyJNIFields: unverified offset %d for %s", offset, k->external_name());
 254       }
 255       #endif
 256 #endif
 257     }
 258   }
 259   guarantee(InstanceKlass::cast(k)->contains_field_offset(offset),
 260       "Bug in native code: jfieldID offset must address interior of object");
 261 }
 262 
 263 // Wrapper to trace JNI functions
 264 
 265 #ifdef ASSERT
 266   Histogram* JNIHistogram;
 267   static volatile int JNIHistogram_lock = 0;
 268 
 269   class JNIHistogramElement : public HistogramElement {
 270     public:
 271      JNIHistogramElement(const char* name);
 272   };
 273 
 274   JNIHistogramElement::JNIHistogramElement(const char* elementName) {
 275     _name = elementName;
 276     uintx count = 0;
 277 
 278     while (Atomic::cmpxchg(1, &JNIHistogram_lock, 0) != 0) {
 279       while (OrderAccess::load_acquire(&JNIHistogram_lock) != 0) {
 280         count +=1;
 281         if ( (WarnOnStalledSpinLock > 0)
 282           && (count % WarnOnStalledSpinLock == 0)) {
 283           warning("JNIHistogram_lock seems to be stalled");
 284         }
 285       }
 286      }
 287 
 288 
 289     if(JNIHistogram == NULL)
 290       JNIHistogram = new Histogram("JNI Call Counts",100);
 291 
 292     JNIHistogram->add_element(this);
 293     Atomic::dec(&JNIHistogram_lock);
 294   }
 295 
 296   #define JNICountWrapper(arg)                                     \
 297      static JNIHistogramElement* e = new JNIHistogramElement(arg); \
 298       /* There is a MT-race condition in VC++. So we need to make sure that that e has been initialized */ \
 299      if (e != NULL) e->increment_count()
 300   #define JNIWrapper(arg) JNICountWrapper(arg);
 301 #else
 302   #define JNIWrapper(arg)
 303 #endif
 304 
 305 
 306 // Implementation of JNI entries
 307 
 308 DT_RETURN_MARK_DECL(DefineClass, jclass
 309                     , HOTSPOT_JNI_DEFINECLASS_RETURN(_ret_ref));
 310 
 311 JNI_ENTRY(jclass, jni_DefineClass(JNIEnv *env, const char *name, jobject loaderRef,
 312                                   const jbyte *buf, jsize bufLen))
 313   JNIWrapper("DefineClass");
 314 
 315   HOTSPOT_JNI_DEFINECLASS_ENTRY(
 316     env, (char*) name, loaderRef, (char*) buf, bufLen);
 317 
 318   jclass cls = NULL;
 319   DT_RETURN_MARK(DefineClass, jclass, (const jclass&)cls);
 320 
 321   TempNewSymbol class_name = NULL;
 322   // Since exceptions can be thrown, class initialization can take place
 323   // if name is NULL no check for class name in .class stream has to be made.
 324   if (name != NULL) {
 325     const int str_len = (int)strlen(name);
 326     if (str_len > Symbol::max_length()) {
 327       // It's impossible to create this class;  the name cannot fit
 328       // into the constant pool.
 329       Exceptions::fthrow(THREAD_AND_LOCATION,
 330                          vmSymbols::java_lang_NoClassDefFoundError(),
 331                          "Class name exceeds maximum length of %d: %s",
 332                          Symbol::max_length(),
 333                          name);
 334       return 0;
 335     }
 336     class_name = SymbolTable::new_symbol(name);
 337   }
 338   ResourceMark rm(THREAD);
 339   ClassFileStream st((u1*)buf, bufLen, NULL, ClassFileStream::verify);
 340   Handle class_loader (THREAD, JNIHandles::resolve(loaderRef));
 341 
 342   if (UsePerfData && !class_loader.is_null()) {
 343     // check whether the current caller thread holds the lock or not.
 344     // If not, increment the corresponding counter
 345     if (ObjectSynchronizer::
 346         query_lock_ownership((JavaThread*)THREAD, class_loader) !=
 347         ObjectSynchronizer::owner_self) {
 348       ClassLoader::sync_JNIDefineClassLockFreeCounter()->inc();
 349     }
 350   }
 351   Klass* k = SystemDictionary::resolve_from_stream(class_name,
 352                                                    class_loader,
 353                                                    Handle(),
 354                                                    &st,
 355                                                    CHECK_NULL);
 356 
 357   if (log_is_enabled(Debug, class, resolve) && k != NULL) {
 358     trace_class_resolution(k);
 359   }
 360 
 361   cls = (jclass)JNIHandles::make_local(
 362     env, k->java_mirror());
 363   return cls;
 364 JNI_END
 365 
 366 
 367 
 368 DT_RETURN_MARK_DECL(FindClass, jclass
 369                     , HOTSPOT_JNI_FINDCLASS_RETURN(_ret_ref));
 370 
 371 JNI_ENTRY(jclass, jni_FindClass(JNIEnv *env, const char *name))
 372   JNIWrapper("FindClass");
 373 
 374   HOTSPOT_JNI_FINDCLASS_ENTRY(env, (char *)name);
 375 
 376   jclass result = NULL;
 377   DT_RETURN_MARK(FindClass, jclass, (const jclass&)result);
 378 
 379   // Sanity check the name:  it cannot be null or larger than the maximum size
 380   // name we can fit in the constant pool.
 381   if (name == NULL) {
 382     THROW_MSG_0(vmSymbols::java_lang_NoClassDefFoundError(), "No class name given");
 383   }
 384   if ((int)strlen(name) > Symbol::max_length()) {
 385     Exceptions::fthrow(THREAD_AND_LOCATION,
 386                        vmSymbols::java_lang_NoClassDefFoundError(),
 387                        "Class name exceeds maximum length of %d: %s",
 388                        Symbol::max_length(),
 389                        name);
 390     return 0;
 391   }
 392 
 393   //%note jni_3
 394   Handle protection_domain;
 395   // Find calling class
 396   Klass* k = thread->security_get_caller_class(0);
 397   // default to the system loader when no context
 398   Handle loader(THREAD, SystemDictionary::java_system_loader());
 399   if (k != NULL) {
 400     // Special handling to make sure JNI_OnLoad and JNI_OnUnload are executed
 401     // in the correct class context.
 402     if (k->class_loader() == NULL &&
 403         k->name() == vmSymbols::java_lang_ClassLoader_NativeLibrary()) {
 404       JavaValue result(T_OBJECT);
 405       JavaCalls::call_static(&result, k,
 406                              vmSymbols::getFromClass_name(),
 407                              vmSymbols::void_class_signature(),
 408                              CHECK_NULL);
 409       // When invoked from JNI_OnLoad, NativeLibrary::getFromClass returns
 410       // a non-NULL Class object.  When invoked from JNI_OnUnload,
 411       // it will return NULL to indicate no context.
 412       oop mirror = (oop) result.get_jobject();
 413       if (mirror != NULL) {
 414         Klass* fromClass = java_lang_Class::as_Klass(mirror);
 415         loader = Handle(THREAD, fromClass->class_loader());
 416         protection_domain = Handle(THREAD, fromClass->protection_domain());
 417       }
 418     } else {
 419       loader = Handle(THREAD, k->class_loader());
 420     }
 421   }
 422 
 423   TempNewSymbol sym = SymbolTable::new_symbol(name);
 424   result = find_class_from_class_loader(env, sym, true, loader,
 425                                         protection_domain, true, thread);
 426 
 427   if (log_is_enabled(Debug, class, resolve) && result != NULL) {
 428     trace_class_resolution(java_lang_Class::as_Klass(JNIHandles::resolve_non_null(result)));
 429   }
 430 
 431   return result;
 432 JNI_END
 433 
 434 DT_RETURN_MARK_DECL(FromReflectedMethod, jmethodID
 435                     , HOTSPOT_JNI_FROMREFLECTEDMETHOD_RETURN((uintptr_t)_ret_ref));
 436 
 437 JNI_ENTRY(jmethodID, jni_FromReflectedMethod(JNIEnv *env, jobject method))
 438   JNIWrapper("FromReflectedMethod");
 439 
 440   HOTSPOT_JNI_FROMREFLECTEDMETHOD_ENTRY(env, method);
 441 
 442   jmethodID ret = NULL;
 443   DT_RETURN_MARK(FromReflectedMethod, jmethodID, (const jmethodID&)ret);
 444 
 445   // method is a handle to a java.lang.reflect.Method object
 446   oop reflected  = JNIHandles::resolve_non_null(method);
 447   oop mirror     = NULL;
 448   int slot       = 0;
 449 
 450   if (reflected->klass() == SystemDictionary::reflect_Constructor_klass()) {
 451     mirror = java_lang_reflect_Constructor::clazz(reflected);
 452     slot   = java_lang_reflect_Constructor::slot(reflected);
 453   } else {
 454     assert(reflected->klass() == SystemDictionary::reflect_Method_klass(), "wrong type");
 455     mirror = java_lang_reflect_Method::clazz(reflected);
 456     slot   = java_lang_reflect_Method::slot(reflected);
 457   }
 458   Klass* k1 = java_lang_Class::as_Klass(mirror);
 459 
 460   // Make sure class is initialized before handing id's out to methods
 461   k1->initialize(CHECK_NULL);
 462   Method* m = InstanceKlass::cast(k1)->method_with_idnum(slot);
 463   ret = m==NULL? NULL : m->jmethod_id();  // return NULL if reflected method deleted
 464   return ret;
 465 JNI_END
 466 
 467 DT_RETURN_MARK_DECL(FromReflectedField, jfieldID
 468                     , HOTSPOT_JNI_FROMREFLECTEDFIELD_RETURN((uintptr_t)_ret_ref));
 469 
 470 JNI_ENTRY(jfieldID, jni_FromReflectedField(JNIEnv *env, jobject field))
 471   JNIWrapper("FromReflectedField");
 472 
 473   HOTSPOT_JNI_FROMREFLECTEDFIELD_ENTRY(env, field);
 474 
 475   jfieldID ret = NULL;
 476   DT_RETURN_MARK(FromReflectedField, jfieldID, (const jfieldID&)ret);
 477 
 478   // field is a handle to a java.lang.reflect.Field object
 479   oop reflected   = JNIHandles::resolve_non_null(field);
 480   oop mirror      = java_lang_reflect_Field::clazz(reflected);
 481   Klass* k1       = java_lang_Class::as_Klass(mirror);
 482   int slot        = java_lang_reflect_Field::slot(reflected);
 483   int modifiers   = java_lang_reflect_Field::modifiers(reflected);
 484 
 485   // Make sure class is initialized before handing id's out to fields
 486   k1->initialize(CHECK_NULL);
 487 
 488   // First check if this is a static field
 489   if (modifiers & JVM_ACC_STATIC) {
 490     intptr_t offset = InstanceKlass::cast(k1)->field_offset( slot );
 491     JNIid* id = InstanceKlass::cast(k1)->jni_id_for(offset);
 492     assert(id != NULL, "corrupt Field object");
 493     debug_only(id->set_is_static_field_id();)
 494     // A jfieldID for a static field is a JNIid specifying the field holder and the offset within the Klass*
 495     ret = jfieldIDWorkaround::to_static_jfieldID(id);
 496     return ret;
 497   }
 498 
 499   // The slot is the index of the field description in the field-array
 500   // The jfieldID is the offset of the field within the object
 501   // It may also have hash bits for k, if VerifyJNIFields is turned on.
 502   intptr_t offset = InstanceKlass::cast(k1)->field_offset( slot );
 503   bool is_flattened = InstanceKlass::cast(k1)->field_is_flattened(slot);
 504   assert(InstanceKlass::cast(k1)->contains_field_offset(offset), "stay within object");
 505   ret = jfieldIDWorkaround::to_instance_jfieldID(k1, offset, is_flattened);
 506   return ret;
 507 JNI_END
 508 
 509 
 510 DT_RETURN_MARK_DECL(ToReflectedMethod, jobject
 511                     , HOTSPOT_JNI_TOREFLECTEDMETHOD_RETURN(_ret_ref));
 512 
 513 JNI_ENTRY(jobject, jni_ToReflectedMethod(JNIEnv *env, jclass cls, jmethodID method_id, jboolean isStatic))
 514   JNIWrapper("ToReflectedMethod");
 515 
 516   HOTSPOT_JNI_TOREFLECTEDMETHOD_ENTRY(env, cls, (uintptr_t) method_id, isStatic);
 517 
 518   jobject ret = NULL;
 519   DT_RETURN_MARK(ToReflectedMethod, jobject, (const jobject&)ret);
 520 
 521   methodHandle m (THREAD, Method::resolve_jmethod_id(method_id));
 522   assert(m->is_static() == (isStatic != 0), "jni_ToReflectedMethod access flags doesn't match");
 523   oop reflection_method;
 524   if (m->is_object_constructor()) {
 525     reflection_method = Reflection::new_constructor(m, CHECK_NULL);
 526   } else {
 527     reflection_method = Reflection::new_method(m, false, CHECK_NULL);
 528   }
 529   ret = JNIHandles::make_local(env, reflection_method);
 530   return ret;
 531 JNI_END
 532 
 533 DT_RETURN_MARK_DECL(GetSuperclass, jclass
 534                     , HOTSPOT_JNI_GETSUPERCLASS_RETURN(_ret_ref));
 535 
 536 JNI_ENTRY(jclass, jni_GetSuperclass(JNIEnv *env, jclass sub))
 537   JNIWrapper("GetSuperclass");
 538 
 539   HOTSPOT_JNI_GETSUPERCLASS_ENTRY(env, sub);
 540 
 541   jclass obj = NULL;
 542   DT_RETURN_MARK(GetSuperclass, jclass, (const jclass&)obj);
 543 
 544   oop mirror = JNIHandles::resolve_non_null(sub);
 545   // primitive classes return NULL
 546   if (java_lang_Class::is_primitive(mirror)) return NULL;
 547 
 548   // Rules of Class.getSuperClass as implemented by KLass::java_super:
 549   // arrays return Object
 550   // interfaces return NULL
 551   // proper classes return Klass::super()
 552   Klass* k = java_lang_Class::as_Klass(mirror);
 553   if (k->is_interface()) return NULL;
 554 
 555   // return mirror for superclass
 556   Klass* super = k->java_super();
 557   // super2 is the value computed by the compiler's getSuperClass intrinsic:
 558   debug_only(Klass* super2 = ( k->is_array_klass()
 559                                  ? SystemDictionary::Object_klass()
 560                                  : k->super() ) );
 561   assert(super == super2,
 562          "java_super computation depends on interface, array, other super");
 563   obj = (super == NULL) ? NULL : (jclass) JNIHandles::make_local(super->java_mirror());
 564   return obj;
 565 JNI_END
 566 
 567 JNI_ENTRY_NO_PRESERVE(jboolean, jni_IsAssignableFrom(JNIEnv *env, jclass sub, jclass super))
 568   JNIWrapper("IsSubclassOf");
 569 
 570   HOTSPOT_JNI_ISASSIGNABLEFROM_ENTRY(env, sub, super);
 571 
 572   oop sub_mirror   = JNIHandles::resolve_non_null(sub);
 573   oop super_mirror = JNIHandles::resolve_non_null(super);
 574   if (java_lang_Class::is_primitive(sub_mirror) ||
 575       java_lang_Class::is_primitive(super_mirror)) {
 576     jboolean ret = (sub_mirror == super_mirror);
 577 
 578     HOTSPOT_JNI_ISASSIGNABLEFROM_RETURN(ret);
 579     return ret;
 580   }
 581   Klass* sub_klass   = java_lang_Class::as_Klass(sub_mirror);
 582   Klass* super_klass = java_lang_Class::as_Klass(super_mirror);
 583   assert(sub_klass != NULL && super_klass != NULL, "invalid arguments to jni_IsAssignableFrom");
 584   jboolean ret = sub_klass->is_subtype_of(super_klass) ?
 585                    JNI_TRUE : JNI_FALSE;
 586   if (sub_klass == super_klass && sub_klass->is_value()) {
 587     // for inline class, V <: V?
 588     ValueKlass* vk = ValueKlass::cast(InstanceKlass::cast(sub_klass));
 589     if (sub_mirror == super_mirror || (sub_mirror == vk->value_mirror() && super_mirror == vk->indirect_mirror())) {
 590       ret = JNI_TRUE;
 591     } else {
 592       ret = JNI_FALSE;
 593     }
 594   }
 595   HOTSPOT_JNI_ISASSIGNABLEFROM_RETURN(ret);
 596   return ret;
 597 JNI_END
 598 
 599 
 600 DT_RETURN_MARK_DECL(Throw, jint
 601                     , HOTSPOT_JNI_THROW_RETURN(_ret_ref));
 602 
 603 JNI_ENTRY(jint, jni_Throw(JNIEnv *env, jthrowable obj))
 604   JNIWrapper("Throw");
 605 
 606   HOTSPOT_JNI_THROW_ENTRY(env, obj);
 607 
 608   jint ret = JNI_OK;
 609   DT_RETURN_MARK(Throw, jint, (const jint&)ret);
 610 
 611   THROW_OOP_(JNIHandles::resolve(obj), JNI_OK);
 612   ShouldNotReachHere();
 613   return 0;  // Mute compiler.
 614 JNI_END
 615 
 616 
 617 DT_RETURN_MARK_DECL(ThrowNew, jint
 618                     , HOTSPOT_JNI_THROWNEW_RETURN(_ret_ref));
 619 
 620 JNI_ENTRY(jint, jni_ThrowNew(JNIEnv *env, jclass clazz, const char *message))
 621   JNIWrapper("ThrowNew");
 622 
 623   HOTSPOT_JNI_THROWNEW_ENTRY(env, clazz, (char *) message);
 624 
 625   jint ret = JNI_OK;
 626   DT_RETURN_MARK(ThrowNew, jint, (const jint&)ret);
 627 
 628   InstanceKlass* k = InstanceKlass::cast(java_lang_Class::as_Klass(JNIHandles::resolve_non_null(clazz)));
 629   Symbol*  name = k->name();
 630   Handle class_loader (THREAD,  k->class_loader());
 631   Handle protection_domain (THREAD, k->protection_domain());
 632   THROW_MSG_LOADER_(name, (char *)message, class_loader, protection_domain, JNI_OK);
 633   ShouldNotReachHere();
 634   return 0;  // Mute compiler.
 635 JNI_END
 636 
 637 
 638 // JNI functions only transform a pending async exception to a synchronous
 639 // exception in ExceptionOccurred and ExceptionCheck calls, since
 640 // delivering an async exception in other places won't change the native
 641 // code's control flow and would be harmful when native code further calls
 642 // JNI functions with a pending exception. Async exception is also checked
 643 // during the call, so ExceptionOccurred/ExceptionCheck won't return
 644 // false but deliver the async exception at the very end during
 645 // state transition.
 646 
 647 static void jni_check_async_exceptions(JavaThread *thread) {
 648   assert(thread == Thread::current(), "must be itself");
 649   thread->check_and_handle_async_exceptions();
 650 }
 651 
 652 JNI_ENTRY_NO_PRESERVE(jthrowable, jni_ExceptionOccurred(JNIEnv *env))
 653   JNIWrapper("ExceptionOccurred");
 654 
 655   HOTSPOT_JNI_EXCEPTIONOCCURRED_ENTRY(env);
 656 
 657   jni_check_async_exceptions(thread);
 658   oop exception = thread->pending_exception();
 659   jthrowable ret = (jthrowable) JNIHandles::make_local(env, exception);
 660 
 661   HOTSPOT_JNI_EXCEPTIONOCCURRED_RETURN(ret);
 662   return ret;
 663 JNI_END
 664 
 665 
 666 JNI_ENTRY_NO_PRESERVE(void, jni_ExceptionDescribe(JNIEnv *env))
 667   JNIWrapper("ExceptionDescribe");
 668 
 669   HOTSPOT_JNI_EXCEPTIONDESCRIBE_ENTRY(env);
 670 
 671   if (thread->has_pending_exception()) {
 672     Handle ex(thread, thread->pending_exception());
 673     thread->clear_pending_exception();
 674     if (ex->is_a(SystemDictionary::ThreadDeath_klass())) {
 675       // Don't print anything if we are being killed.
 676     } else {
 677       jio_fprintf(defaultStream::error_stream(), "Exception ");
 678       if (thread != NULL && thread->threadObj() != NULL) {
 679         ResourceMark rm(THREAD);
 680         jio_fprintf(defaultStream::error_stream(),
 681         "in thread \"%s\" ", thread->get_thread_name());
 682       }
 683       if (ex->is_a(SystemDictionary::Throwable_klass())) {
 684         JavaValue result(T_VOID);
 685         JavaCalls::call_virtual(&result,
 686                                 ex,
 687                                 SystemDictionary::Throwable_klass(),
 688                                 vmSymbols::printStackTrace_name(),
 689                                 vmSymbols::void_method_signature(),
 690                                 THREAD);
 691         // If an exception is thrown in the call it gets thrown away. Not much
 692         // we can do with it. The native code that calls this, does not check
 693         // for the exception - hence, it might still be in the thread when DestroyVM gets
 694         // called, potentially causing a few asserts to trigger - since no pending exception
 695         // is expected.
 696         CLEAR_PENDING_EXCEPTION;
 697       } else {
 698         ResourceMark rm(THREAD);
 699         jio_fprintf(defaultStream::error_stream(),
 700         ". Uncaught exception of type %s.",
 701         ex->klass()->external_name());
 702       }
 703     }
 704   }
 705 
 706   HOTSPOT_JNI_EXCEPTIONDESCRIBE_RETURN();
 707 JNI_END
 708 
 709 
 710 JNI_ENTRY_NO_PRESERVE(void, jni_ExceptionClear(JNIEnv *env))
 711   JNIWrapper("ExceptionClear");
 712 
 713   HOTSPOT_JNI_EXCEPTIONCLEAR_ENTRY(env);
 714 
 715   // The jni code might be using this API to clear java thrown exception.
 716   // So just mark jvmti thread exception state as exception caught.
 717   JvmtiThreadState *state = JavaThread::current()->jvmti_thread_state();
 718   if (state != NULL && state->is_exception_detected()) {
 719     state->set_exception_caught();
 720   }
 721   thread->clear_pending_exception();
 722 
 723   HOTSPOT_JNI_EXCEPTIONCLEAR_RETURN();
 724 JNI_END
 725 
 726 
 727 JNI_ENTRY(void, jni_FatalError(JNIEnv *env, const char *msg))
 728   JNIWrapper("FatalError");
 729 
 730   HOTSPOT_JNI_FATALERROR_ENTRY(env, (char *) msg);
 731 
 732   tty->print_cr("FATAL ERROR in native method: %s", msg);
 733   thread->print_stack();
 734   os::abort(); // Dump core and abort
 735 JNI_END
 736 
 737 
 738 JNI_ENTRY(jint, jni_PushLocalFrame(JNIEnv *env, jint capacity))
 739   JNIWrapper("PushLocalFrame");
 740 
 741   HOTSPOT_JNI_PUSHLOCALFRAME_ENTRY(env, capacity);
 742 
 743   //%note jni_11
 744   if (capacity < 0 ||
 745       ((MaxJNILocalCapacity > 0) && (capacity > MaxJNILocalCapacity))) {
 746     HOTSPOT_JNI_PUSHLOCALFRAME_RETURN((uint32_t)JNI_ERR);
 747     return JNI_ERR;
 748   }
 749   JNIHandleBlock* old_handles = thread->active_handles();
 750   JNIHandleBlock* new_handles = JNIHandleBlock::allocate_block(thread);
 751   assert(new_handles != NULL, "should not be NULL");
 752   new_handles->set_pop_frame_link(old_handles);
 753   thread->set_active_handles(new_handles);
 754   jint ret = JNI_OK;
 755   HOTSPOT_JNI_PUSHLOCALFRAME_RETURN(ret);
 756   return ret;
 757 JNI_END
 758 
 759 
 760 JNI_ENTRY(jobject, jni_PopLocalFrame(JNIEnv *env, jobject result))
 761   JNIWrapper("PopLocalFrame");
 762 
 763   HOTSPOT_JNI_POPLOCALFRAME_ENTRY(env, result);
 764 
 765   //%note jni_11
 766   Handle result_handle(thread, JNIHandles::resolve(result));
 767   JNIHandleBlock* old_handles = thread->active_handles();
 768   JNIHandleBlock* new_handles = old_handles->pop_frame_link();
 769   if (new_handles != NULL) {
 770     // As a sanity check we only release the handle blocks if the pop_frame_link is not NULL.
 771     // This way code will still work if PopLocalFrame is called without a corresponding
 772     // PushLocalFrame call. Note that we set the pop_frame_link to NULL explicitly, otherwise
 773     // the release_block call will release the blocks.
 774     thread->set_active_handles(new_handles);
 775     old_handles->set_pop_frame_link(NULL);              // clear link we won't release new_handles below
 776     JNIHandleBlock::release_block(old_handles, thread); // may block
 777     result = JNIHandles::make_local(thread, result_handle());
 778   }
 779   HOTSPOT_JNI_POPLOCALFRAME_RETURN(result);
 780   return result;
 781 JNI_END
 782 
 783 
 784 JNI_ENTRY(jobject, jni_NewGlobalRef(JNIEnv *env, jobject ref))
 785   JNIWrapper("NewGlobalRef");
 786 
 787   HOTSPOT_JNI_NEWGLOBALREF_ENTRY(env, ref);
 788 
 789   Handle ref_handle(thread, JNIHandles::resolve(ref));
 790   jobject ret = JNIHandles::make_global(ref_handle);
 791 
 792   HOTSPOT_JNI_NEWGLOBALREF_RETURN(ret);
 793   return ret;
 794 JNI_END
 795 
 796 // Must be JNI_ENTRY (with HandleMark)
 797 JNI_ENTRY_NO_PRESERVE(void, jni_DeleteGlobalRef(JNIEnv *env, jobject ref))
 798   JNIWrapper("DeleteGlobalRef");
 799 
 800   HOTSPOT_JNI_DELETEGLOBALREF_ENTRY(env, ref);
 801 
 802   JNIHandles::destroy_global(ref);
 803 
 804   HOTSPOT_JNI_DELETEGLOBALREF_RETURN();
 805 JNI_END
 806 
 807 JNI_ENTRY_NO_PRESERVE(void, jni_DeleteLocalRef(JNIEnv *env, jobject obj))
 808   JNIWrapper("DeleteLocalRef");
 809 
 810   HOTSPOT_JNI_DELETELOCALREF_ENTRY(env, obj);
 811 
 812   JNIHandles::destroy_local(obj);
 813 
 814   HOTSPOT_JNI_DELETELOCALREF_RETURN();
 815 JNI_END
 816 
 817 JNI_ENTRY_NO_PRESERVE(jboolean, jni_IsSameObject(JNIEnv *env, jobject r1, jobject r2))
 818   JNIWrapper("IsSameObject");
 819 
 820   HOTSPOT_JNI_ISSAMEOBJECT_ENTRY(env, r1, r2);
 821 
 822   jboolean ret = JNIHandles::is_same_object(r1, r2) ? JNI_TRUE : JNI_FALSE;
 823 
 824   HOTSPOT_JNI_ISSAMEOBJECT_RETURN(ret);
 825   return ret;
 826 JNI_END
 827 
 828 
 829 JNI_ENTRY(jobject, jni_NewLocalRef(JNIEnv *env, jobject ref))
 830   JNIWrapper("NewLocalRef");
 831 
 832   HOTSPOT_JNI_NEWLOCALREF_ENTRY(env, ref);
 833 
 834   jobject ret = JNIHandles::make_local(env, JNIHandles::resolve(ref));
 835 
 836   HOTSPOT_JNI_NEWLOCALREF_RETURN(ret);
 837   return ret;
 838 JNI_END
 839 
 840 JNI_LEAF(jint, jni_EnsureLocalCapacity(JNIEnv *env, jint capacity))
 841   JNIWrapper("EnsureLocalCapacity");
 842 
 843   HOTSPOT_JNI_ENSURELOCALCAPACITY_ENTRY(env, capacity);
 844 
 845   jint ret;
 846   if (capacity >= 0 &&
 847       ((MaxJNILocalCapacity <= 0) || (capacity <= MaxJNILocalCapacity))) {
 848     ret = JNI_OK;
 849   } else {
 850     ret = JNI_ERR;
 851   }
 852 
 853   HOTSPOT_JNI_ENSURELOCALCAPACITY_RETURN(ret);
 854   return ret;
 855 JNI_END
 856 
 857 // Return the Handle Type
 858 JNI_LEAF(jobjectRefType, jni_GetObjectRefType(JNIEnv *env, jobject obj))
 859   JNIWrapper("GetObjectRefType");
 860 
 861   HOTSPOT_JNI_GETOBJECTREFTYPE_ENTRY(env, obj);
 862 
 863   jobjectRefType ret = JNIInvalidRefType;
 864   if (obj != NULL) {
 865     ret = JNIHandles::handle_type(thread, obj);
 866   }
 867 
 868   HOTSPOT_JNI_GETOBJECTREFTYPE_RETURN((void *) ret);
 869   return ret;
 870 JNI_END
 871 
 872 
 873 class JNI_ArgumentPusher : public SignatureIterator {
 874  protected:
 875   JavaCallArguments*  _arguments;
 876 
 877   virtual void get_bool   () = 0;
 878   virtual void get_char   () = 0;
 879   virtual void get_short  () = 0;
 880   virtual void get_byte   () = 0;
 881   virtual void get_int    () = 0;
 882   virtual void get_long   () = 0;
 883   virtual void get_float  () = 0;
 884   virtual void get_double () = 0;
 885   virtual void get_object () = 0;
 886   virtual void get_valuetype() = 0;
 887 
 888   JNI_ArgumentPusher(Symbol* signature) : SignatureIterator(signature) {
 889     this->_return_type = T_ILLEGAL;
 890     _arguments = NULL;
 891   }
 892 
 893  public:
 894   virtual void iterate( uint64_t fingerprint ) = 0;
 895 
 896   void set_java_argument_object(JavaCallArguments *arguments) { _arguments = arguments; }
 897 
 898   inline void do_bool()                     { if (!is_return_type()) get_bool();   }
 899   inline void do_char()                     { if (!is_return_type()) get_char();   }
 900   inline void do_short()                    { if (!is_return_type()) get_short();  }
 901   inline void do_byte()                     { if (!is_return_type()) get_byte();   }
 902   inline void do_int()                      { if (!is_return_type()) get_int();    }
 903   inline void do_long()                     { if (!is_return_type()) get_long();   }
 904   inline void do_float()                    { if (!is_return_type()) get_float();  }
 905   inline void do_double()                   { if (!is_return_type()) get_double(); }
 906   inline void do_object(int begin, int end) { if (!is_return_type()) get_object(); }
 907   inline void do_valuetype(int begin, int end) { if (!is_return_type()) get_valuetype();  }
 908   inline void do_array(int begin, int end)  { if (!is_return_type()) get_object(); } // do_array uses get_object -- there is no get_array
 909   inline void do_void()                     { }
 910 
 911   JavaCallArguments* arguments()     { return _arguments; }
 912   void push_receiver(Handle h)       { _arguments->push_oop(h); }
 913 };
 914 
 915 
 916 class JNI_ArgumentPusherVaArg : public JNI_ArgumentPusher {
 917  protected:
 918   va_list _ap;
 919 
 920   inline void get_bool()   {
 921     // Normalize boolean arguments from native code by converting 1-255 to JNI_TRUE and
 922     // 0 to JNI_FALSE.  Boolean return values from native are normalized the same in
 923     // TemplateInterpreterGenerator::generate_result_handler_for and
 924     // SharedRuntime::generate_native_wrapper.
 925     jboolean b = va_arg(_ap, jint);
 926     _arguments->push_int((jint)(b == 0 ? JNI_FALSE : JNI_TRUE));
 927   }
 928   inline void get_char()   { _arguments->push_int(va_arg(_ap, jint)); } // char is coerced to int when using va_arg
 929   inline void get_short()  { _arguments->push_int(va_arg(_ap, jint)); } // short is coerced to int when using va_arg
 930   inline void get_byte()   { _arguments->push_int(va_arg(_ap, jint)); } // byte is coerced to int when using va_arg
 931   inline void get_int()    { _arguments->push_int(va_arg(_ap, jint)); }
 932 
 933   // each of these paths is exercized by the various jck Call[Static,Nonvirtual,][Void,Int,..]Method[A,V,] tests
 934 
 935   inline void get_long()   { _arguments->push_long(va_arg(_ap, jlong)); }
 936   inline void get_float()  { _arguments->push_float((jfloat)va_arg(_ap, jdouble)); } // float is coerced to double w/ va_arg
 937   inline void get_double() { _arguments->push_double(va_arg(_ap, jdouble)); }
 938   inline void get_object() { _arguments->push_jobject(va_arg(_ap, jobject)); }
 939   inline void get_valuetype() { _arguments->push_jobject(va_arg(_ap, jobject)); }
 940 
 941   inline void set_ap(va_list rap) {
 942     va_copy(_ap, rap);
 943   }
 944 
 945  public:
 946   JNI_ArgumentPusherVaArg(Symbol* signature, va_list rap)
 947        : JNI_ArgumentPusher(signature) {
 948     set_ap(rap);
 949   }
 950   JNI_ArgumentPusherVaArg(jmethodID method_id, va_list rap)
 951       : JNI_ArgumentPusher(Method::resolve_jmethod_id(method_id)->signature()) {
 952     set_ap(rap);
 953   }
 954 
 955   // Optimized path if we have the bitvector form of signature
 956   void iterate( uint64_t fingerprint ) {
 957     if (fingerprint == (uint64_t)CONST64(-1)) {
 958       SignatureIterator::iterate(); // Must be too many arguments
 959     } else {
 960       _return_type = (BasicType)((fingerprint >> static_feature_size) &
 961                                   result_feature_mask);
 962 
 963       assert(fingerprint, "Fingerprint should not be 0");
 964       fingerprint = fingerprint >> (static_feature_size + result_feature_size);
 965       while ( 1 ) {
 966         switch ( fingerprint & parameter_feature_mask ) {
 967           case bool_parm:
 968             get_bool();
 969             break;
 970           case char_parm:
 971             get_char();
 972             break;
 973           case short_parm:
 974             get_short();
 975             break;
 976           case byte_parm:
 977             get_byte();
 978             break;
 979           case int_parm:
 980             get_int();
 981             break;
 982           case obj_parm:
 983             get_object();
 984             break;
 985           case long_parm:
 986             get_long();
 987             break;
 988           case float_parm:
 989             get_float();
 990             break;
 991           case double_parm:
 992             get_double();
 993             break;
 994           case done_parm:
 995             return;
 996             break;
 997           default:
 998             ShouldNotReachHere();
 999             break;
1000         }
1001         fingerprint >>= parameter_feature_size;
1002       }
1003     }
1004   }
1005 };
1006 
1007 
1008 class JNI_ArgumentPusherArray : public JNI_ArgumentPusher {
1009  protected:
1010   const jvalue *_ap;
1011 
1012   inline void get_bool()   {
1013     // Normalize boolean arguments from native code by converting 1-255 to JNI_TRUE and
1014     // 0 to JNI_FALSE.  Boolean return values from native are normalized the same in
1015     // TemplateInterpreterGenerator::generate_result_handler_for and
1016     // SharedRuntime::generate_native_wrapper.
1017     jboolean b = (_ap++)->z;
1018     _arguments->push_int((jint)(b == 0 ? JNI_FALSE : JNI_TRUE));
1019   }
1020   inline void get_char()   { _arguments->push_int((jint)(_ap++)->c); }
1021   inline void get_short()  { _arguments->push_int((jint)(_ap++)->s); }
1022   inline void get_byte()   { _arguments->push_int((jint)(_ap++)->b); }
1023   inline void get_int()    { _arguments->push_int((jint)(_ap++)->i); }
1024 
1025   inline void get_long()   { _arguments->push_long((_ap++)->j);  }
1026   inline void get_float()  { _arguments->push_float((_ap++)->f); }
1027   inline void get_double() { _arguments->push_double((_ap++)->d);}
1028   inline void get_object() { _arguments->push_jobject((_ap++)->l); }
1029   // value types are implemented with oops too
1030   inline void get_valuetype() { _arguments->push_jobject((_ap++)->l); }
1031 
1032   inline void set_ap(const jvalue *rap) { _ap = rap; }
1033 
1034  public:
1035   JNI_ArgumentPusherArray(Symbol* signature, const jvalue *rap)
1036        : JNI_ArgumentPusher(signature) {
1037     set_ap(rap);
1038   }
1039   JNI_ArgumentPusherArray(jmethodID method_id, const jvalue *rap)
1040       : JNI_ArgumentPusher(Method::resolve_jmethod_id(method_id)->signature()) {
1041     set_ap(rap);
1042   }
1043 
1044   // Optimized path if we have the bitvector form of signature
1045   void iterate( uint64_t fingerprint ) {
1046     if (fingerprint == (uint64_t)CONST64(-1)) {
1047       SignatureIterator::iterate(); // Must be too many arguments
1048     } else {
1049       _return_type = (BasicType)((fingerprint >> static_feature_size) &
1050                                   result_feature_mask);
1051       assert(fingerprint, "Fingerprint should not be 0");
1052       fingerprint = fingerprint >> (static_feature_size + result_feature_size);
1053       while ( 1 ) {
1054         switch ( fingerprint & parameter_feature_mask ) {
1055           case bool_parm:
1056             get_bool();
1057             break;
1058           case char_parm:
1059             get_char();
1060             break;
1061           case short_parm:
1062             get_short();
1063             break;
1064           case byte_parm:
1065             get_byte();
1066             break;
1067           case int_parm:
1068             get_int();
1069             break;
1070           case obj_parm:
1071             get_object();
1072             break;
1073           case long_parm:
1074             get_long();
1075             break;
1076           case float_parm:
1077             get_float();
1078             break;
1079           case double_parm:
1080             get_double();
1081             break;
1082           case done_parm:
1083             return;
1084             break;
1085           default:
1086             ShouldNotReachHere();
1087             break;
1088         }
1089         fingerprint >>= parameter_feature_size;
1090       }
1091     }
1092   }
1093 };
1094 
1095 
1096 enum JNICallType {
1097   JNI_STATIC,
1098   JNI_VIRTUAL,
1099   JNI_NONVIRTUAL
1100 };
1101 
1102 
1103 
1104 static void jni_invoke_static(JNIEnv *env, JavaValue* result, jobject receiver, JNICallType call_type, jmethodID method_id, JNI_ArgumentPusher *args, TRAPS) {
1105   methodHandle method(THREAD, Method::resolve_jmethod_id(method_id));
1106 
1107   // Create object to hold arguments for the JavaCall, and associate it with
1108   // the jni parser
1109   ResourceMark rm(THREAD);
1110   int number_of_parameters = method->size_of_parameters();
1111   JavaCallArguments java_args(number_of_parameters);
1112   args->set_java_argument_object(&java_args);
1113 
1114   assert(method->is_static(), "method should be static");
1115 
1116   // Fill out JavaCallArguments object
1117   args->iterate( Fingerprinter(method).fingerprint() );
1118   // Initialize result type
1119   result->set_type(args->get_ret_type());
1120 
1121   // Invoke the method. Result is returned as oop.
1122   JavaCalls::call(result, method, &java_args, CHECK);
1123 
1124   // Convert result
1125   if (is_reference_type(result->get_type())) {
1126     result->set_jobject(JNIHandles::make_local(env, (oop) result->get_jobject()));
1127   }
1128 }
1129 
1130 
1131 static void jni_invoke_nonstatic(JNIEnv *env, JavaValue* result, jobject receiver, JNICallType call_type, jmethodID method_id, JNI_ArgumentPusher *args, TRAPS) {
1132   oop recv = JNIHandles::resolve(receiver);
1133   if (recv == NULL) {
1134     THROW(vmSymbols::java_lang_NullPointerException());
1135   }
1136   Handle h_recv(THREAD, recv);
1137 
1138   int number_of_parameters;
1139   Method* selected_method;
1140   {
1141     Method* m = Method::resolve_jmethod_id(method_id);
1142     number_of_parameters = m->size_of_parameters();
1143     Klass* holder = m->method_holder();
1144     if (call_type != JNI_VIRTUAL) {
1145         selected_method = m;
1146     } else if (!m->has_itable_index()) {
1147       // non-interface call -- for that little speed boost, don't handlize
1148       debug_only(NoSafepointVerifier nosafepoint;)
1149       // jni_GetMethodID makes sure class is linked and initialized
1150       // so m should have a valid vtable index.
1151       assert(m->valid_vtable_index(), "no valid vtable index");
1152       int vtbl_index = m->vtable_index();
1153       if (vtbl_index != Method::nonvirtual_vtable_index) {
1154         selected_method = h_recv->klass()->method_at_vtable(vtbl_index);
1155       } else {
1156         // final method
1157         selected_method = m;
1158       }
1159     } else {
1160       // interface call
1161       int itbl_index = m->itable_index();
1162       Klass* k = h_recv->klass();
1163       selected_method = InstanceKlass::cast(k)->method_at_itable(holder, itbl_index, CHECK);
1164     }
1165   }
1166 
1167   methodHandle method(THREAD, selected_method);
1168 
1169   // Create object to hold arguments for the JavaCall, and associate it with
1170   // the jni parser
1171   ResourceMark rm(THREAD);
1172   JavaCallArguments java_args(number_of_parameters);
1173   args->set_java_argument_object(&java_args);
1174 
1175   // handle arguments
1176   assert(!method->is_static(), "method %s should not be static", method->name_and_sig_as_C_string());
1177   args->push_receiver(h_recv); // Push jobject handle
1178 
1179   // Fill out JavaCallArguments object
1180   args->iterate( Fingerprinter(method).fingerprint() );
1181   // Initialize result type
1182   result->set_type(args->get_ret_type());
1183 
1184   // Invoke the method. Result is returned as oop.
1185   JavaCalls::call(result, method, &java_args, CHECK);
1186 
1187   // Convert result
1188   if (is_reference_type(result->get_type())) {
1189     result->set_jobject(JNIHandles::make_local(env, (oop) result->get_jobject()));
1190   }
1191 }
1192 
1193 
1194 static instanceOop alloc_object(jclass clazz, TRAPS) {
1195   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(clazz));
1196   if (k == NULL) {
1197     ResourceMark rm(THREAD);
1198     THROW_(vmSymbols::java_lang_InstantiationException(), NULL);
1199   }
1200   k->check_valid_for_instantiation(false, CHECK_NULL);
1201   k->initialize(CHECK_NULL);
1202   instanceOop ih = InstanceKlass::cast(k)->allocate_instance(THREAD);
1203   return ih;
1204 }
1205 
1206 DT_RETURN_MARK_DECL(AllocObject, jobject
1207                     , HOTSPOT_JNI_ALLOCOBJECT_RETURN(_ret_ref));
1208 
1209 JNI_ENTRY(jobject, jni_AllocObject(JNIEnv *env, jclass clazz))
1210   JNIWrapper("AllocObject");
1211 
1212   HOTSPOT_JNI_ALLOCOBJECT_ENTRY(env, clazz);
1213 
1214   jobject ret = NULL;
1215   DT_RETURN_MARK(AllocObject, jobject, (const jobject&)ret);
1216 
1217   instanceOop i = alloc_object(clazz, CHECK_NULL);
1218   ret = JNIHandles::make_local(env, i);
1219   return ret;
1220 JNI_END
1221 
1222 DT_RETURN_MARK_DECL(NewObjectA, jobject
1223                     , HOTSPOT_JNI_NEWOBJECTA_RETURN(_ret_ref));
1224 
1225 JNI_ENTRY(jobject, jni_NewObjectA(JNIEnv *env, jclass clazz, jmethodID methodID, const jvalue *args))
1226   JNIWrapper("NewObjectA");
1227 
1228   HOTSPOT_JNI_NEWOBJECTA_ENTRY(env, clazz, (uintptr_t) methodID);
1229 
1230   jobject obj = NULL;
1231   DT_RETURN_MARK(NewObjectA, jobject, (const jobject)obj);
1232 
1233   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(clazz));
1234   if (k == NULL) {
1235     ResourceMark rm(THREAD);
1236     THROW_(vmSymbols::java_lang_InstantiationException(), NULL);
1237   }
1238 
1239   if (!k->is_value()) {
1240     instanceOop i = alloc_object(clazz, CHECK_NULL);
1241     obj = JNIHandles::make_local(env, i);
1242     JavaValue jvalue(T_VOID);
1243     JNI_ArgumentPusherArray ap(methodID, args);
1244     jni_invoke_nonstatic(env, &jvalue, obj, JNI_NONVIRTUAL, methodID, &ap, CHECK_NULL);
1245   } else {
1246     JavaValue jvalue(T_VALUETYPE);
1247     JNI_ArgumentPusherArray ap(methodID, args);
1248     jni_invoke_static(env, &jvalue, NULL, JNI_STATIC, methodID, &ap, CHECK_NULL);
1249     obj = jvalue.get_jobject();
1250   }
1251   return obj;
1252   JNI_END
1253 
1254 
1255 DT_RETURN_MARK_DECL(NewObjectV, jobject
1256                     , HOTSPOT_JNI_NEWOBJECTV_RETURN(_ret_ref));
1257 
1258 JNI_ENTRY(jobject, jni_NewObjectV(JNIEnv *env, jclass clazz, jmethodID methodID, va_list args))
1259   JNIWrapper("NewObjectV");
1260 
1261   HOTSPOT_JNI_NEWOBJECTV_ENTRY(env, clazz, (uintptr_t) methodID);
1262 
1263   jobject obj = NULL;
1264   DT_RETURN_MARK(NewObjectV, jobject, (const jobject&)obj);
1265 
1266   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(clazz));
1267   if (k == NULL) {
1268     ResourceMark rm(THREAD);
1269     THROW_(vmSymbols::java_lang_InstantiationException(), NULL);
1270   }
1271 
1272   if (!k->is_value()) {
1273     instanceOop i = alloc_object(clazz, CHECK_NULL);
1274     obj = JNIHandles::make_local(env, i);
1275     JavaValue jvalue(T_VOID);
1276     JNI_ArgumentPusherVaArg ap(methodID, args);
1277     jni_invoke_nonstatic(env, &jvalue, obj, JNI_NONVIRTUAL, methodID, &ap, CHECK_NULL);
1278   } else {
1279     JavaValue jvalue(T_VALUETYPE);
1280     JNI_ArgumentPusherVaArg ap(methodID, args);
1281     jni_invoke_static(env, &jvalue, NULL, JNI_STATIC, methodID, &ap, CHECK_NULL);
1282     obj = jvalue.get_jobject();
1283   }
1284   return obj;
1285 JNI_END
1286 
1287 
1288 DT_RETURN_MARK_DECL(NewObject, jobject
1289                     , HOTSPOT_JNI_NEWOBJECT_RETURN(_ret_ref));
1290 
1291 JNI_ENTRY(jobject, jni_NewObject(JNIEnv *env, jclass clazz, jmethodID methodID, ...))
1292   JNIWrapper("NewObject");
1293 
1294   HOTSPOT_JNI_NEWOBJECT_ENTRY(env, clazz, (uintptr_t) methodID);
1295 
1296   jobject obj = NULL;
1297   DT_RETURN_MARK(NewObject, jobject, (const jobject&)obj);
1298 
1299   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(clazz));
1300   if (k == NULL) {
1301     ResourceMark rm(THREAD);
1302     THROW_(vmSymbols::java_lang_InstantiationException(), NULL);
1303   }
1304 
1305   if (!k->is_value()) {
1306     instanceOop i = alloc_object(clazz, CHECK_NULL);
1307     obj = JNIHandles::make_local(env, i);
1308     va_list args;
1309     va_start(args, methodID);
1310     JavaValue jvalue(T_VOID);
1311     JNI_ArgumentPusherVaArg ap(methodID, args);
1312     jni_invoke_nonstatic(env, &jvalue, obj, JNI_NONVIRTUAL, methodID, &ap, CHECK_NULL);
1313     va_end(args);
1314   } else {
1315     va_list args;
1316     va_start(args, methodID);
1317     JavaValue jvalue(T_VALUETYPE);
1318     JNI_ArgumentPusherVaArg ap(methodID, args);
1319     jni_invoke_static(env, &jvalue, NULL, JNI_STATIC, methodID, &ap, CHECK_NULL);
1320     va_end(args);
1321     obj = jvalue.get_jobject();
1322   }
1323   return obj;
1324 JNI_END
1325 
1326 
1327 JNI_ENTRY(jclass, jni_GetObjectClass(JNIEnv *env, jobject obj))
1328   JNIWrapper("GetObjectClass");
1329 
1330   HOTSPOT_JNI_GETOBJECTCLASS_ENTRY(env, obj);
1331 
1332   Klass* k = JNIHandles::resolve_non_null(obj)->klass();
1333   jclass ret =
1334     (jclass) JNIHandles::make_local(env, k->java_mirror());
1335 
1336   HOTSPOT_JNI_GETOBJECTCLASS_RETURN(ret);
1337   return ret;
1338 JNI_END
1339 
1340 JNI_ENTRY_NO_PRESERVE(jboolean, jni_IsInstanceOf(JNIEnv *env, jobject obj, jclass clazz))
1341   JNIWrapper("IsInstanceOf");
1342 
1343   HOTSPOT_JNI_ISINSTANCEOF_ENTRY(env, obj, clazz);
1344 
1345   jboolean ret = JNI_TRUE;
1346   if (obj != NULL) {
1347     ret = JNI_FALSE;
1348     Klass* k = java_lang_Class::as_Klass(
1349       JNIHandles::resolve_non_null(clazz));
1350     if (k != NULL) {
1351       ret = JNIHandles::resolve_non_null(obj)->is_a(k) ? JNI_TRUE : JNI_FALSE;
1352     }
1353   }
1354 
1355   HOTSPOT_JNI_ISINSTANCEOF_RETURN(ret);
1356   return ret;
1357 JNI_END
1358 
1359 
1360 static jmethodID get_method_id(JNIEnv *env, jclass clazz, const char *name_str,
1361                                const char *sig, bool is_static, TRAPS) {
1362   // %%%% This code should probably just call into a method in the LinkResolver
1363   //
1364   // The class should have been loaded (we have an instance of the class
1365   // passed in) so the method and signature should already be in the symbol
1366   // table.  If they're not there, the method doesn't exist.
1367   const char *name_to_probe = (name_str == NULL)
1368                         ? vmSymbols::object_initializer_name()->as_C_string()
1369                         : name_str;
1370   TempNewSymbol name = SymbolTable::probe(name_to_probe, (int)strlen(name_to_probe));
1371   TempNewSymbol signature = SymbolTable::probe(sig, (int)strlen(sig));
1372 
1373   if (name == NULL || signature == NULL) {
1374     THROW_MSG_0(vmSymbols::java_lang_NoSuchMethodError(), name_str);
1375   }
1376 
1377   Klass* klass = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(clazz));
1378 
1379   // Throw a NoSuchMethodError exception if we have an instance of a
1380   // primitive java.lang.Class
1381   if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(clazz))) {
1382     ResourceMark rm;
1383     THROW_MSG_0(vmSymbols::java_lang_NoSuchMethodError(), err_msg("%s%s.%s%s", is_static ? "static " : "", klass->signature_name(), name_str, sig));
1384   }
1385 
1386   // Make sure class is linked and initialized before handing id's out to
1387   // Method*s.
1388   klass->initialize(CHECK_NULL);
1389 
1390   Method* m;
1391   if (name == vmSymbols::object_initializer_name() ||
1392       name == vmSymbols::class_initializer_name()) {
1393     // Never search superclasses for constructors
1394     if (klass->is_instance_klass()) {
1395       m = InstanceKlass::cast(klass)->find_method(name, signature);
1396     } else {
1397       m = NULL;
1398     }
1399   } else {
1400     m = klass->lookup_method(name, signature);
1401     if (m == NULL &&  klass->is_instance_klass()) {
1402       m = InstanceKlass::cast(klass)->lookup_method_in_ordered_interfaces(name, signature);
1403     }
1404   }
1405   if (m == NULL || (m->is_static() != is_static)) {
1406     ResourceMark rm;
1407     THROW_MSG_0(vmSymbols::java_lang_NoSuchMethodError(), err_msg("%s%s.%s%s", is_static ? "static " : "", klass->signature_name(), name_str, sig));
1408   }
1409   return m->jmethod_id();
1410 }
1411 
1412 
1413 JNI_ENTRY(jmethodID, jni_GetMethodID(JNIEnv *env, jclass clazz,
1414           const char *name, const char *sig))
1415   JNIWrapper("GetMethodID");
1416   HOTSPOT_JNI_GETMETHODID_ENTRY(env, clazz, (char *) name, (char *) sig);
1417   jmethodID ret = get_method_id(env, clazz, name, sig, false, thread);
1418   HOTSPOT_JNI_GETMETHODID_RETURN((uintptr_t) ret);
1419   return ret;
1420 JNI_END
1421 
1422 
1423 JNI_ENTRY(jmethodID, jni_GetStaticMethodID(JNIEnv *env, jclass clazz,
1424           const char *name, const char *sig))
1425   JNIWrapper("GetStaticMethodID");
1426   HOTSPOT_JNI_GETSTATICMETHODID_ENTRY(env, (char *) clazz, (char *) name, (char *)sig);
1427   jmethodID ret = get_method_id(env, clazz, name, sig, true, thread);
1428   HOTSPOT_JNI_GETSTATICMETHODID_RETURN((uintptr_t) ret);
1429   return ret;
1430 JNI_END
1431 
1432 
1433 
1434 //
1435 // Calling Methods
1436 //
1437 
1438 
1439 #define DEFINE_CALLMETHOD(ResultType, Result, Tag \
1440                           , EntryProbe, ReturnProbe)    \
1441 \
1442   DT_RETURN_MARK_DECL_FOR(Result, Call##Result##Method, ResultType \
1443                           , ReturnProbe);                          \
1444 \
1445 JNI_ENTRY(ResultType, \
1446           jni_Call##Result##Method(JNIEnv *env, jobject obj, jmethodID methodID, ...)) \
1447   JNIWrapper("Call" XSTR(Result) "Method"); \
1448 \
1449   EntryProbe; \
1450   ResultType ret = 0;\
1451   DT_RETURN_MARK_FOR(Result, Call##Result##Method, ResultType, \
1452                      (const ResultType&)ret);\
1453 \
1454   va_list args; \
1455   va_start(args, methodID); \
1456   JavaValue jvalue(Tag); \
1457   JNI_ArgumentPusherVaArg ap(methodID, args); \
1458   jni_invoke_nonstatic(env, &jvalue, obj, JNI_VIRTUAL, methodID, &ap, CHECK_0); \
1459   va_end(args); \
1460   ret = jvalue.get_##ResultType(); \
1461   return ret;\
1462 JNI_END
1463 
1464 // the runtime type of subword integral basic types is integer
1465 DEFINE_CALLMETHOD(jboolean, Boolean, T_BOOLEAN
1466                   , HOTSPOT_JNI_CALLBOOLEANMETHOD_ENTRY(env, obj, (uintptr_t)methodID),
1467                   HOTSPOT_JNI_CALLBOOLEANMETHOD_RETURN(_ret_ref))
1468 DEFINE_CALLMETHOD(jbyte,    Byte,    T_BYTE
1469                   , HOTSPOT_JNI_CALLBYTEMETHOD_ENTRY(env, obj, (uintptr_t)methodID),
1470                   HOTSPOT_JNI_CALLBYTEMETHOD_RETURN(_ret_ref))
1471 DEFINE_CALLMETHOD(jchar,    Char,    T_CHAR
1472                   , HOTSPOT_JNI_CALLCHARMETHOD_ENTRY(env, obj, (uintptr_t)methodID),
1473                   HOTSPOT_JNI_CALLCHARMETHOD_RETURN(_ret_ref))
1474 DEFINE_CALLMETHOD(jshort,   Short,   T_SHORT
1475                   , HOTSPOT_JNI_CALLSHORTMETHOD_ENTRY(env, obj, (uintptr_t)methodID),
1476                   HOTSPOT_JNI_CALLSHORTMETHOD_RETURN(_ret_ref))
1477 
1478 DEFINE_CALLMETHOD(jobject,  Object,  T_OBJECT
1479                   , HOTSPOT_JNI_CALLOBJECTMETHOD_ENTRY(env, obj, (uintptr_t)methodID),
1480                   HOTSPOT_JNI_CALLOBJECTMETHOD_RETURN(_ret_ref))
1481 DEFINE_CALLMETHOD(jint,     Int,     T_INT,
1482                   HOTSPOT_JNI_CALLINTMETHOD_ENTRY(env, obj, (uintptr_t)methodID),
1483                   HOTSPOT_JNI_CALLINTMETHOD_RETURN(_ret_ref))
1484 DEFINE_CALLMETHOD(jlong,    Long,    T_LONG
1485                   , HOTSPOT_JNI_CALLLONGMETHOD_ENTRY(env, obj, (uintptr_t)methodID),
1486                   HOTSPOT_JNI_CALLLONGMETHOD_RETURN(_ret_ref))
1487 // Float and double probes don't return value because dtrace doesn't currently support it
1488 DEFINE_CALLMETHOD(jfloat,   Float,   T_FLOAT
1489                   , HOTSPOT_JNI_CALLFLOATMETHOD_ENTRY(env, obj, (uintptr_t)methodID),
1490                   HOTSPOT_JNI_CALLFLOATMETHOD_RETURN())
1491 DEFINE_CALLMETHOD(jdouble,  Double,  T_DOUBLE
1492                   , HOTSPOT_JNI_CALLDOUBLEMETHOD_ENTRY(env, obj, (uintptr_t)methodID),
1493                   HOTSPOT_JNI_CALLDOUBLEMETHOD_RETURN())
1494 
1495 #define DEFINE_CALLMETHODV(ResultType, Result, Tag \
1496                           , EntryProbe, ReturnProbe)    \
1497 \
1498   DT_RETURN_MARK_DECL_FOR(Result, Call##Result##MethodV, ResultType \
1499                           , ReturnProbe);                          \
1500 \
1501 JNI_ENTRY(ResultType, \
1502           jni_Call##Result##MethodV(JNIEnv *env, jobject obj, jmethodID methodID, va_list args)) \
1503   JNIWrapper("Call" XSTR(Result) "MethodV"); \
1504 \
1505   EntryProbe;\
1506   ResultType ret = 0;\
1507   DT_RETURN_MARK_FOR(Result, Call##Result##MethodV, ResultType, \
1508                      (const ResultType&)ret);\
1509 \
1510   JavaValue jvalue(Tag); \
1511   JNI_ArgumentPusherVaArg ap(methodID, args); \
1512   jni_invoke_nonstatic(env, &jvalue, obj, JNI_VIRTUAL, methodID, &ap, CHECK_0); \
1513   ret = jvalue.get_##ResultType(); \
1514   return ret;\
1515 JNI_END
1516 
1517 // the runtime type of subword integral basic types is integer
1518 DEFINE_CALLMETHODV(jboolean, Boolean, T_BOOLEAN
1519                   , HOTSPOT_JNI_CALLBOOLEANMETHODV_ENTRY(env, obj, (uintptr_t)methodID),
1520                   HOTSPOT_JNI_CALLBOOLEANMETHODV_RETURN(_ret_ref))
1521 DEFINE_CALLMETHODV(jbyte,    Byte,    T_BYTE
1522                   , HOTSPOT_JNI_CALLBYTEMETHODV_ENTRY(env, obj, (uintptr_t)methodID),
1523                   HOTSPOT_JNI_CALLBYTEMETHODV_RETURN(_ret_ref))
1524 DEFINE_CALLMETHODV(jchar,    Char,    T_CHAR
1525                   , HOTSPOT_JNI_CALLCHARMETHODV_ENTRY(env, obj, (uintptr_t)methodID),
1526                   HOTSPOT_JNI_CALLCHARMETHODV_RETURN(_ret_ref))
1527 DEFINE_CALLMETHODV(jshort,   Short,   T_SHORT
1528                   , HOTSPOT_JNI_CALLSHORTMETHODV_ENTRY(env, obj, (uintptr_t)methodID),
1529                   HOTSPOT_JNI_CALLSHORTMETHODV_RETURN(_ret_ref))
1530 
1531 DEFINE_CALLMETHODV(jobject,  Object,  T_OBJECT
1532                   , HOTSPOT_JNI_CALLOBJECTMETHODV_ENTRY(env, obj, (uintptr_t)methodID),
1533                   HOTSPOT_JNI_CALLOBJECTMETHODV_RETURN(_ret_ref))
1534 DEFINE_CALLMETHODV(jint,     Int,     T_INT,
1535                   HOTSPOT_JNI_CALLINTMETHODV_ENTRY(env, obj, (uintptr_t)methodID),
1536                   HOTSPOT_JNI_CALLINTMETHODV_RETURN(_ret_ref))
1537 DEFINE_CALLMETHODV(jlong,    Long,    T_LONG
1538                   , HOTSPOT_JNI_CALLLONGMETHODV_ENTRY(env, obj, (uintptr_t)methodID),
1539                   HOTSPOT_JNI_CALLLONGMETHODV_RETURN(_ret_ref))
1540 // Float and double probes don't return value because dtrace doesn't currently support it
1541 DEFINE_CALLMETHODV(jfloat,   Float,   T_FLOAT
1542                   , HOTSPOT_JNI_CALLFLOATMETHODV_ENTRY(env, obj, (uintptr_t)methodID),
1543                   HOTSPOT_JNI_CALLFLOATMETHODV_RETURN())
1544 DEFINE_CALLMETHODV(jdouble,  Double,  T_DOUBLE
1545                   , HOTSPOT_JNI_CALLDOUBLEMETHODV_ENTRY(env, obj, (uintptr_t)methodID),
1546                   HOTSPOT_JNI_CALLDOUBLEMETHODV_RETURN())
1547 
1548 #define DEFINE_CALLMETHODA(ResultType, Result, Tag \
1549                           , EntryProbe, ReturnProbe)    \
1550 \
1551   DT_RETURN_MARK_DECL_FOR(Result, Call##Result##MethodA, ResultType \
1552                           , ReturnProbe);                          \
1553 \
1554 JNI_ENTRY(ResultType, \
1555           jni_Call##Result##MethodA(JNIEnv *env, jobject obj, jmethodID methodID, const jvalue *args)) \
1556   JNIWrapper("Call" XSTR(Result) "MethodA"); \
1557   EntryProbe; \
1558   ResultType ret = 0;\
1559   DT_RETURN_MARK_FOR(Result, Call##Result##MethodA, ResultType, \
1560                      (const ResultType&)ret);\
1561 \
1562   JavaValue jvalue(Tag); \
1563   JNI_ArgumentPusherArray ap(methodID, args); \
1564   jni_invoke_nonstatic(env, &jvalue, obj, JNI_VIRTUAL, methodID, &ap, CHECK_0); \
1565   ret = jvalue.get_##ResultType(); \
1566   return ret;\
1567 JNI_END
1568 
1569 // the runtime type of subword integral basic types is integer
1570 DEFINE_CALLMETHODA(jboolean, Boolean, T_BOOLEAN
1571                   , HOTSPOT_JNI_CALLBOOLEANMETHODA_ENTRY(env, obj, (uintptr_t)methodID),
1572                   HOTSPOT_JNI_CALLBOOLEANMETHODA_RETURN(_ret_ref))
1573 DEFINE_CALLMETHODA(jbyte,    Byte,    T_BYTE
1574                   , HOTSPOT_JNI_CALLBYTEMETHODA_ENTRY(env, obj, (uintptr_t)methodID),
1575                   HOTSPOT_JNI_CALLBYTEMETHODA_RETURN(_ret_ref))
1576 DEFINE_CALLMETHODA(jchar,    Char,    T_CHAR
1577                   , HOTSPOT_JNI_CALLCHARMETHODA_ENTRY(env, obj, (uintptr_t)methodID),
1578                   HOTSPOT_JNI_CALLCHARMETHODA_RETURN(_ret_ref))
1579 DEFINE_CALLMETHODA(jshort,   Short,   T_SHORT
1580                   , HOTSPOT_JNI_CALLSHORTMETHODA_ENTRY(env, obj, (uintptr_t)methodID),
1581                   HOTSPOT_JNI_CALLSHORTMETHODA_RETURN(_ret_ref))
1582 
1583 DEFINE_CALLMETHODA(jobject,  Object,  T_OBJECT
1584                   , HOTSPOT_JNI_CALLOBJECTMETHODA_ENTRY(env, obj, (uintptr_t)methodID),
1585                   HOTSPOT_JNI_CALLOBJECTMETHODA_RETURN(_ret_ref))
1586 DEFINE_CALLMETHODA(jint,     Int,     T_INT,
1587                   HOTSPOT_JNI_CALLINTMETHODA_ENTRY(env, obj, (uintptr_t)methodID),
1588                   HOTSPOT_JNI_CALLINTMETHODA_RETURN(_ret_ref))
1589 DEFINE_CALLMETHODA(jlong,    Long,    T_LONG
1590                   , HOTSPOT_JNI_CALLLONGMETHODA_ENTRY(env, obj, (uintptr_t)methodID),
1591                   HOTSPOT_JNI_CALLLONGMETHODA_RETURN(_ret_ref))
1592 // Float and double probes don't return value because dtrace doesn't currently support it
1593 DEFINE_CALLMETHODA(jfloat,   Float,   T_FLOAT
1594                   , HOTSPOT_JNI_CALLFLOATMETHODA_ENTRY(env, obj, (uintptr_t)methodID),
1595                   HOTSPOT_JNI_CALLFLOATMETHODA_RETURN())
1596 DEFINE_CALLMETHODA(jdouble,  Double,  T_DOUBLE
1597                   , HOTSPOT_JNI_CALLDOUBLEMETHODA_ENTRY(env, obj, (uintptr_t)methodID),
1598                   HOTSPOT_JNI_CALLDOUBLEMETHODA_RETURN())
1599 
1600 DT_VOID_RETURN_MARK_DECL(CallVoidMethod, HOTSPOT_JNI_CALLVOIDMETHOD_RETURN());
1601 DT_VOID_RETURN_MARK_DECL(CallVoidMethodV, HOTSPOT_JNI_CALLVOIDMETHODV_RETURN());
1602 DT_VOID_RETURN_MARK_DECL(CallVoidMethodA, HOTSPOT_JNI_CALLVOIDMETHODA_RETURN());
1603 
1604 
1605 JNI_ENTRY(void, jni_CallVoidMethod(JNIEnv *env, jobject obj, jmethodID methodID, ...))
1606   JNIWrapper("CallVoidMethod");
1607   HOTSPOT_JNI_CALLVOIDMETHOD_ENTRY(env, obj, (uintptr_t) methodID);
1608   DT_VOID_RETURN_MARK(CallVoidMethod);
1609 
1610   va_list args;
1611   va_start(args, methodID);
1612   JavaValue jvalue(T_VOID);
1613   JNI_ArgumentPusherVaArg ap(methodID, args);
1614   jni_invoke_nonstatic(env, &jvalue, obj, JNI_VIRTUAL, methodID, &ap, CHECK);
1615   va_end(args);
1616 JNI_END
1617 
1618 
1619 JNI_ENTRY(void, jni_CallVoidMethodV(JNIEnv *env, jobject obj, jmethodID methodID, va_list args))
1620   JNIWrapper("CallVoidMethodV");
1621   HOTSPOT_JNI_CALLVOIDMETHODV_ENTRY(env, obj, (uintptr_t) methodID);
1622   DT_VOID_RETURN_MARK(CallVoidMethodV);
1623 
1624   JavaValue jvalue(T_VOID);
1625   JNI_ArgumentPusherVaArg ap(methodID, args);
1626   jni_invoke_nonstatic(env, &jvalue, obj, JNI_VIRTUAL, methodID, &ap, CHECK);
1627 JNI_END
1628 
1629 
1630 JNI_ENTRY(void, jni_CallVoidMethodA(JNIEnv *env, jobject obj, jmethodID methodID, const jvalue *args))
1631   JNIWrapper("CallVoidMethodA");
1632   HOTSPOT_JNI_CALLVOIDMETHODA_ENTRY(env, obj, (uintptr_t) methodID);
1633   DT_VOID_RETURN_MARK(CallVoidMethodA);
1634 
1635   JavaValue jvalue(T_VOID);
1636   JNI_ArgumentPusherArray ap(methodID, args);
1637   jni_invoke_nonstatic(env, &jvalue, obj, JNI_VIRTUAL, methodID, &ap, CHECK);
1638 JNI_END
1639 
1640 
1641 
1642 #define DEFINE_CALLNONVIRTUALMETHOD(ResultType, Result, Tag \
1643                                     , EntryProbe, ReturnProbe)      \
1644 \
1645   DT_RETURN_MARK_DECL_FOR(Result, CallNonvirtual##Result##Method, ResultType \
1646                           , ReturnProbe);\
1647 \
1648 JNI_ENTRY(ResultType, \
1649           jni_CallNonvirtual##Result##Method(JNIEnv *env, jobject obj, jclass cls, jmethodID methodID, ...)) \
1650   JNIWrapper("CallNonvitual" XSTR(Result) "Method"); \
1651 \
1652   EntryProbe;\
1653   ResultType ret;\
1654   DT_RETURN_MARK_FOR(Result, CallNonvirtual##Result##Method, ResultType, \
1655                      (const ResultType&)ret);\
1656 \
1657   va_list args; \
1658   va_start(args, methodID); \
1659   JavaValue jvalue(Tag); \
1660   JNI_ArgumentPusherVaArg ap(methodID, args); \
1661   jni_invoke_nonstatic(env, &jvalue, obj, JNI_NONVIRTUAL, methodID, &ap, CHECK_0); \
1662   va_end(args); \
1663   ret = jvalue.get_##ResultType(); \
1664   return ret;\
1665 JNI_END
1666 
1667 // the runtime type of subword integral basic types is integer
1668 DEFINE_CALLNONVIRTUALMETHOD(jboolean, Boolean, T_BOOLEAN
1669                             , HOTSPOT_JNI_CALLNONVIRTUALBOOLEANMETHOD_ENTRY(env, obj, cls, (uintptr_t)methodID),
1670                             HOTSPOT_JNI_CALLNONVIRTUALBOOLEANMETHOD_RETURN(_ret_ref))
1671 DEFINE_CALLNONVIRTUALMETHOD(jbyte,    Byte,    T_BYTE
1672                             , HOTSPOT_JNI_CALLNONVIRTUALBYTEMETHOD_ENTRY(env, obj, cls, (uintptr_t)methodID),
1673                             HOTSPOT_JNI_CALLNONVIRTUALBYTEMETHOD_RETURN(_ret_ref))
1674 DEFINE_CALLNONVIRTUALMETHOD(jchar,    Char,    T_CHAR
1675                             , HOTSPOT_JNI_CALLNONVIRTUALCHARMETHOD_ENTRY(env, obj, cls, (uintptr_t)methodID),
1676                             HOTSPOT_JNI_CALLNONVIRTUALCHARMETHOD_RETURN(_ret_ref))
1677 DEFINE_CALLNONVIRTUALMETHOD(jshort,   Short,   T_SHORT
1678                             , HOTSPOT_JNI_CALLNONVIRTUALSHORTMETHOD_ENTRY(env, obj, cls, (uintptr_t)methodID),
1679                             HOTSPOT_JNI_CALLNONVIRTUALSHORTMETHOD_RETURN(_ret_ref))
1680 
1681 DEFINE_CALLNONVIRTUALMETHOD(jobject,  Object,  T_OBJECT
1682                             , HOTSPOT_JNI_CALLNONVIRTUALOBJECTMETHOD_ENTRY(env, obj, cls, (uintptr_t)methodID),
1683                             HOTSPOT_JNI_CALLNONVIRTUALOBJECTMETHOD_RETURN(_ret_ref))
1684 DEFINE_CALLNONVIRTUALMETHOD(jint,     Int,     T_INT
1685                             , HOTSPOT_JNI_CALLNONVIRTUALINTMETHOD_ENTRY(env, obj, cls, (uintptr_t)methodID),
1686                             HOTSPOT_JNI_CALLNONVIRTUALINTMETHOD_RETURN(_ret_ref))
1687 DEFINE_CALLNONVIRTUALMETHOD(jlong,    Long,    T_LONG
1688                             , HOTSPOT_JNI_CALLNONVIRTUALLONGMETHOD_ENTRY(env, obj, cls, (uintptr_t)methodID),
1689 // Float and double probes don't return value because dtrace doesn't currently support it
1690                             HOTSPOT_JNI_CALLNONVIRTUALLONGMETHOD_RETURN(_ret_ref))
1691 DEFINE_CALLNONVIRTUALMETHOD(jfloat,   Float,   T_FLOAT
1692                             , HOTSPOT_JNI_CALLNONVIRTUALFLOATMETHOD_ENTRY(env, obj, cls, (uintptr_t)methodID),
1693                             HOTSPOT_JNI_CALLNONVIRTUALFLOATMETHOD_RETURN())
1694 DEFINE_CALLNONVIRTUALMETHOD(jdouble,  Double,  T_DOUBLE
1695                             , HOTSPOT_JNI_CALLNONVIRTUALDOUBLEMETHOD_ENTRY(env, obj, cls, (uintptr_t)methodID),
1696                             HOTSPOT_JNI_CALLNONVIRTUALDOUBLEMETHOD_RETURN())
1697 
1698 #define DEFINE_CALLNONVIRTUALMETHODV(ResultType, Result, Tag \
1699                                     , EntryProbe, ReturnProbe)      \
1700 \
1701   DT_RETURN_MARK_DECL_FOR(Result, CallNonvirtual##Result##MethodV, ResultType \
1702                           , ReturnProbe);\
1703 \
1704 JNI_ENTRY(ResultType, \
1705           jni_CallNonvirtual##Result##MethodV(JNIEnv *env, jobject obj, jclass cls, jmethodID methodID, va_list args)) \
1706   JNIWrapper("CallNonvitual" XSTR(Result) "MethodV"); \
1707 \
1708   EntryProbe;\
1709   ResultType ret;\
1710   DT_RETURN_MARK_FOR(Result, CallNonvirtual##Result##MethodV, ResultType, \
1711                      (const ResultType&)ret);\
1712 \
1713   JavaValue jvalue(Tag); \
1714   JNI_ArgumentPusherVaArg ap(methodID, args); \
1715   jni_invoke_nonstatic(env, &jvalue, obj, JNI_NONVIRTUAL, methodID, &ap, CHECK_0); \
1716   ret = jvalue.get_##ResultType(); \
1717   return ret;\
1718 JNI_END
1719 
1720 // the runtime type of subword integral basic types is integer
1721 DEFINE_CALLNONVIRTUALMETHODV(jboolean, Boolean, T_BOOLEAN
1722                             , HOTSPOT_JNI_CALLNONVIRTUALBOOLEANMETHODV_ENTRY(env, obj, cls, (uintptr_t)methodID),
1723                             HOTSPOT_JNI_CALLNONVIRTUALBOOLEANMETHODV_RETURN(_ret_ref))
1724 DEFINE_CALLNONVIRTUALMETHODV(jbyte,    Byte,    T_BYTE
1725                             , HOTSPOT_JNI_CALLNONVIRTUALBYTEMETHODV_ENTRY(env, obj, cls, (uintptr_t)methodID),
1726                             HOTSPOT_JNI_CALLNONVIRTUALBYTEMETHODV_RETURN(_ret_ref))
1727 DEFINE_CALLNONVIRTUALMETHODV(jchar,    Char,    T_CHAR
1728                             , HOTSPOT_JNI_CALLNONVIRTUALCHARMETHODV_ENTRY(env, obj, cls, (uintptr_t)methodID),
1729                             HOTSPOT_JNI_CALLNONVIRTUALCHARMETHODV_RETURN(_ret_ref))
1730 DEFINE_CALLNONVIRTUALMETHODV(jshort,   Short,   T_SHORT
1731                             , HOTSPOT_JNI_CALLNONVIRTUALSHORTMETHODV_ENTRY(env, obj, cls, (uintptr_t)methodID),
1732                             HOTSPOT_JNI_CALLNONVIRTUALSHORTMETHODV_RETURN(_ret_ref))
1733 
1734 DEFINE_CALLNONVIRTUALMETHODV(jobject,  Object,  T_OBJECT
1735                             , HOTSPOT_JNI_CALLNONVIRTUALOBJECTMETHODV_ENTRY(env, obj, cls, (uintptr_t)methodID),
1736                             HOTSPOT_JNI_CALLNONVIRTUALOBJECTMETHODV_RETURN(_ret_ref))
1737 DEFINE_CALLNONVIRTUALMETHODV(jint,     Int,     T_INT
1738                             , HOTSPOT_JNI_CALLNONVIRTUALINTMETHODV_ENTRY(env, obj, cls, (uintptr_t)methodID),
1739                             HOTSPOT_JNI_CALLNONVIRTUALINTMETHODV_RETURN(_ret_ref))
1740 DEFINE_CALLNONVIRTUALMETHODV(jlong,    Long,    T_LONG
1741                             , HOTSPOT_JNI_CALLNONVIRTUALLONGMETHODV_ENTRY(env, obj, cls, (uintptr_t)methodID),
1742 // Float and double probes don't return value because dtrace doesn't currently support it
1743                             HOTSPOT_JNI_CALLNONVIRTUALLONGMETHODV_RETURN(_ret_ref))
1744 DEFINE_CALLNONVIRTUALMETHODV(jfloat,   Float,   T_FLOAT
1745                             , HOTSPOT_JNI_CALLNONVIRTUALFLOATMETHODV_ENTRY(env, obj, cls, (uintptr_t)methodID),
1746                             HOTSPOT_JNI_CALLNONVIRTUALFLOATMETHODV_RETURN())
1747 DEFINE_CALLNONVIRTUALMETHODV(jdouble,  Double,  T_DOUBLE
1748                             , HOTSPOT_JNI_CALLNONVIRTUALDOUBLEMETHODV_ENTRY(env, obj, cls, (uintptr_t)methodID),
1749                             HOTSPOT_JNI_CALLNONVIRTUALDOUBLEMETHODV_RETURN())
1750 
1751 #define DEFINE_CALLNONVIRTUALMETHODA(ResultType, Result, Tag \
1752                                     , EntryProbe, ReturnProbe)      \
1753 \
1754   DT_RETURN_MARK_DECL_FOR(Result, CallNonvirtual##Result##MethodA, ResultType \
1755                           , ReturnProbe);\
1756 \
1757 JNI_ENTRY(ResultType, \
1758           jni_CallNonvirtual##Result##MethodA(JNIEnv *env, jobject obj, jclass cls, jmethodID methodID, const jvalue *args)) \
1759   JNIWrapper("CallNonvitual" XSTR(Result) "MethodA"); \
1760 \
1761   EntryProbe;\
1762   ResultType ret;\
1763   DT_RETURN_MARK_FOR(Result, CallNonvirtual##Result##MethodA, ResultType, \
1764                      (const ResultType&)ret);\
1765 \
1766   JavaValue jvalue(Tag); \
1767   JNI_ArgumentPusherArray ap(methodID, args); \
1768   jni_invoke_nonstatic(env, &jvalue, obj, JNI_NONVIRTUAL, methodID, &ap, CHECK_0); \
1769   ret = jvalue.get_##ResultType(); \
1770   return ret;\
1771 JNI_END
1772 
1773 // the runtime type of subword integral basic types is integer
1774 DEFINE_CALLNONVIRTUALMETHODA(jboolean, Boolean, T_BOOLEAN
1775                             , HOTSPOT_JNI_CALLNONVIRTUALBOOLEANMETHODA_ENTRY(env, obj, cls, (uintptr_t)methodID),
1776                             HOTSPOT_JNI_CALLNONVIRTUALBOOLEANMETHODA_RETURN(_ret_ref))
1777 DEFINE_CALLNONVIRTUALMETHODA(jbyte,    Byte,    T_BYTE
1778                             , HOTSPOT_JNI_CALLNONVIRTUALBYTEMETHODA_ENTRY(env, obj, cls, (uintptr_t)methodID),
1779                             HOTSPOT_JNI_CALLNONVIRTUALBYTEMETHODA_RETURN(_ret_ref))
1780 DEFINE_CALLNONVIRTUALMETHODA(jchar,    Char,    T_CHAR
1781                             , HOTSPOT_JNI_CALLNONVIRTUALCHARMETHODA_ENTRY(env, obj, cls, (uintptr_t)methodID),
1782                             HOTSPOT_JNI_CALLNONVIRTUALCHARMETHODA_RETURN(_ret_ref))
1783 DEFINE_CALLNONVIRTUALMETHODA(jshort,   Short,   T_SHORT
1784                             , HOTSPOT_JNI_CALLNONVIRTUALSHORTMETHODA_ENTRY(env, obj, cls, (uintptr_t)methodID),
1785                             HOTSPOT_JNI_CALLNONVIRTUALSHORTMETHODA_RETURN(_ret_ref))
1786 
1787 DEFINE_CALLNONVIRTUALMETHODA(jobject,  Object,  T_OBJECT
1788                             , HOTSPOT_JNI_CALLNONVIRTUALOBJECTMETHODA_ENTRY(env, obj, cls, (uintptr_t)methodID),
1789                             HOTSPOT_JNI_CALLNONVIRTUALOBJECTMETHODA_RETURN(_ret_ref))
1790 DEFINE_CALLNONVIRTUALMETHODA(jint,     Int,     T_INT
1791                             , HOTSPOT_JNI_CALLNONVIRTUALINTMETHODA_ENTRY(env, obj, cls, (uintptr_t)methodID),
1792                             HOTSPOT_JNI_CALLNONVIRTUALINTMETHODA_RETURN(_ret_ref))
1793 DEFINE_CALLNONVIRTUALMETHODA(jlong,    Long,    T_LONG
1794                             , HOTSPOT_JNI_CALLNONVIRTUALLONGMETHODA_ENTRY(env, obj, cls, (uintptr_t)methodID),
1795 // Float and double probes don't return value because dtrace doesn't currently support it
1796                             HOTSPOT_JNI_CALLNONVIRTUALLONGMETHODA_RETURN(_ret_ref))
1797 DEFINE_CALLNONVIRTUALMETHODA(jfloat,   Float,   T_FLOAT
1798                             , HOTSPOT_JNI_CALLNONVIRTUALFLOATMETHODA_ENTRY(env, obj, cls, (uintptr_t)methodID),
1799                             HOTSPOT_JNI_CALLNONVIRTUALFLOATMETHODA_RETURN())
1800 DEFINE_CALLNONVIRTUALMETHODA(jdouble,  Double,  T_DOUBLE
1801                             , HOTSPOT_JNI_CALLNONVIRTUALDOUBLEMETHODA_ENTRY(env, obj, cls, (uintptr_t)methodID),
1802                             HOTSPOT_JNI_CALLNONVIRTUALDOUBLEMETHODA_RETURN())
1803 
1804 DT_VOID_RETURN_MARK_DECL(CallNonvirtualVoidMethod
1805                          , HOTSPOT_JNI_CALLNONVIRTUALVOIDMETHOD_RETURN());
1806 DT_VOID_RETURN_MARK_DECL(CallNonvirtualVoidMethodV
1807                          , HOTSPOT_JNI_CALLNONVIRTUALVOIDMETHODV_RETURN());
1808 DT_VOID_RETURN_MARK_DECL(CallNonvirtualVoidMethodA
1809                          , HOTSPOT_JNI_CALLNONVIRTUALVOIDMETHODA_RETURN());
1810 
1811 JNI_ENTRY(void, jni_CallNonvirtualVoidMethod(JNIEnv *env, jobject obj, jclass cls, jmethodID methodID, ...))
1812   JNIWrapper("CallNonvirtualVoidMethod");
1813 
1814   HOTSPOT_JNI_CALLNONVIRTUALVOIDMETHOD_ENTRY(env, obj, cls, (uintptr_t) methodID);
1815   DT_VOID_RETURN_MARK(CallNonvirtualVoidMethod);
1816 
1817   va_list args;
1818   va_start(args, methodID);
1819   JavaValue jvalue(T_VOID);
1820   JNI_ArgumentPusherVaArg ap(methodID, args);
1821   jni_invoke_nonstatic(env, &jvalue, obj, JNI_NONVIRTUAL, methodID, &ap, CHECK);
1822   va_end(args);
1823 JNI_END
1824 
1825 
1826 JNI_ENTRY(void, jni_CallNonvirtualVoidMethodV(JNIEnv *env, jobject obj, jclass cls, jmethodID methodID, va_list args))
1827   JNIWrapper("CallNonvirtualVoidMethodV");
1828 
1829   HOTSPOT_JNI_CALLNONVIRTUALVOIDMETHODV_ENTRY(
1830                env, obj, cls, (uintptr_t) methodID);
1831   DT_VOID_RETURN_MARK(CallNonvirtualVoidMethodV);
1832 
1833   JavaValue jvalue(T_VOID);
1834   JNI_ArgumentPusherVaArg ap(methodID, args);
1835   jni_invoke_nonstatic(env, &jvalue, obj, JNI_NONVIRTUAL, methodID, &ap, CHECK);
1836 JNI_END
1837 
1838 
1839 JNI_ENTRY(void, jni_CallNonvirtualVoidMethodA(JNIEnv *env, jobject obj, jclass cls, jmethodID methodID, const jvalue *args))
1840   JNIWrapper("CallNonvirtualVoidMethodA");
1841   HOTSPOT_JNI_CALLNONVIRTUALVOIDMETHODA_ENTRY(
1842                 env, obj, cls, (uintptr_t) methodID);
1843   DT_VOID_RETURN_MARK(CallNonvirtualVoidMethodA);
1844   JavaValue jvalue(T_VOID);
1845   JNI_ArgumentPusherArray ap(methodID, args);
1846   jni_invoke_nonstatic(env, &jvalue, obj, JNI_NONVIRTUAL, methodID, &ap, CHECK);
1847 JNI_END
1848 
1849 
1850 
1851 #define DEFINE_CALLSTATICMETHOD(ResultType, Result, Tag \
1852                                 , EntryProbe, ResultProbe) \
1853 \
1854   DT_RETURN_MARK_DECL_FOR(Result, CallStatic##Result##Method, ResultType \
1855                           , ResultProbe);                               \
1856 \
1857 JNI_ENTRY(ResultType, \
1858           jni_CallStatic##Result##Method(JNIEnv *env, jclass cls, jmethodID methodID, ...)) \
1859   JNIWrapper("CallStatic" XSTR(Result) "Method"); \
1860 \
1861   EntryProbe; \
1862   ResultType ret = 0;\
1863   DT_RETURN_MARK_FOR(Result, CallStatic##Result##Method, ResultType, \
1864                      (const ResultType&)ret);\
1865 \
1866   va_list args; \
1867   va_start(args, methodID); \
1868   JavaValue jvalue(Tag); \
1869   JNI_ArgumentPusherVaArg ap(methodID, args); \
1870   jni_invoke_static(env, &jvalue, NULL, JNI_STATIC, methodID, &ap, CHECK_0); \
1871   va_end(args); \
1872   ret = jvalue.get_##ResultType(); \
1873   return ret;\
1874 JNI_END
1875 
1876 // the runtime type of subword integral basic types is integer
1877 DEFINE_CALLSTATICMETHOD(jboolean, Boolean, T_BOOLEAN
1878                         , HOTSPOT_JNI_CALLSTATICBOOLEANMETHOD_ENTRY(env, cls, (uintptr_t)methodID),
1879                         HOTSPOT_JNI_CALLSTATICBOOLEANMETHOD_RETURN(_ret_ref));
1880 DEFINE_CALLSTATICMETHOD(jbyte,    Byte,    T_BYTE
1881                         , HOTSPOT_JNI_CALLSTATICBYTEMETHOD_ENTRY(env, cls, (uintptr_t)methodID),
1882                         HOTSPOT_JNI_CALLSTATICBYTEMETHOD_RETURN(_ret_ref));
1883 DEFINE_CALLSTATICMETHOD(jchar,    Char,    T_CHAR
1884                         , HOTSPOT_JNI_CALLSTATICCHARMETHOD_ENTRY(env, cls, (uintptr_t)methodID),
1885                         HOTSPOT_JNI_CALLSTATICCHARMETHOD_RETURN(_ret_ref));
1886 DEFINE_CALLSTATICMETHOD(jshort,   Short,   T_SHORT
1887                         , HOTSPOT_JNI_CALLSTATICSHORTMETHOD_ENTRY(env, cls, (uintptr_t)methodID),
1888                         HOTSPOT_JNI_CALLSTATICSHORTMETHOD_RETURN(_ret_ref));
1889 
1890 DEFINE_CALLSTATICMETHOD(jobject,  Object,  T_OBJECT
1891                         , HOTSPOT_JNI_CALLSTATICOBJECTMETHOD_ENTRY(env, cls, (uintptr_t)methodID),
1892                         HOTSPOT_JNI_CALLSTATICOBJECTMETHOD_RETURN(_ret_ref));
1893 DEFINE_CALLSTATICMETHOD(jint,     Int,     T_INT
1894                         , HOTSPOT_JNI_CALLSTATICINTMETHOD_ENTRY(env, cls, (uintptr_t)methodID),
1895                         HOTSPOT_JNI_CALLSTATICINTMETHOD_RETURN(_ret_ref));
1896 DEFINE_CALLSTATICMETHOD(jlong,    Long,    T_LONG
1897                         , HOTSPOT_JNI_CALLSTATICLONGMETHOD_ENTRY(env, cls, (uintptr_t)methodID),
1898                         HOTSPOT_JNI_CALLSTATICLONGMETHOD_RETURN(_ret_ref));
1899 // Float and double probes don't return value because dtrace doesn't currently support it
1900 DEFINE_CALLSTATICMETHOD(jfloat,   Float,   T_FLOAT
1901                         , HOTSPOT_JNI_CALLSTATICFLOATMETHOD_ENTRY(env, cls, (uintptr_t)methodID),
1902                         HOTSPOT_JNI_CALLSTATICFLOATMETHOD_RETURN());
1903 DEFINE_CALLSTATICMETHOD(jdouble,  Double,  T_DOUBLE
1904                         , HOTSPOT_JNI_CALLSTATICDOUBLEMETHOD_ENTRY(env, cls, (uintptr_t)methodID),
1905                         HOTSPOT_JNI_CALLSTATICDOUBLEMETHOD_RETURN());
1906 
1907 #define DEFINE_CALLSTATICMETHODV(ResultType, Result, Tag \
1908                                 , EntryProbe, ResultProbe) \
1909 \
1910   DT_RETURN_MARK_DECL_FOR(Result, CallStatic##Result##MethodV, ResultType \
1911                           , ResultProbe);                               \
1912 \
1913 JNI_ENTRY(ResultType, \
1914           jni_CallStatic##Result##MethodV(JNIEnv *env, jclass cls, jmethodID methodID, va_list args)) \
1915   JNIWrapper("CallStatic" XSTR(Result) "MethodV"); \
1916 \
1917   EntryProbe; \
1918   ResultType ret = 0;\
1919   DT_RETURN_MARK_FOR(Result, CallStatic##Result##MethodV, ResultType, \
1920                      (const ResultType&)ret);\
1921 \
1922   JavaValue jvalue(Tag); \
1923   JNI_ArgumentPusherVaArg ap(methodID, args); \
1924   /* Make sure class is initialized before trying to invoke its method */ \
1925   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls)); \
1926   k->initialize(CHECK_0); \
1927   jni_invoke_static(env, &jvalue, NULL, JNI_STATIC, methodID, &ap, CHECK_0); \
1928   va_end(args); \
1929   ret = jvalue.get_##ResultType(); \
1930   return ret;\
1931 JNI_END
1932 
1933 // the runtime type of subword integral basic types is integer
1934 DEFINE_CALLSTATICMETHODV(jboolean, Boolean, T_BOOLEAN
1935                         , HOTSPOT_JNI_CALLSTATICBOOLEANMETHODV_ENTRY(env, cls, (uintptr_t)methodID),
1936                         HOTSPOT_JNI_CALLSTATICBOOLEANMETHODV_RETURN(_ret_ref));
1937 DEFINE_CALLSTATICMETHODV(jbyte,    Byte,    T_BYTE
1938                         , HOTSPOT_JNI_CALLSTATICBYTEMETHODV_ENTRY(env, cls, (uintptr_t)methodID),
1939                         HOTSPOT_JNI_CALLSTATICBYTEMETHODV_RETURN(_ret_ref));
1940 DEFINE_CALLSTATICMETHODV(jchar,    Char,    T_CHAR
1941                         , HOTSPOT_JNI_CALLSTATICCHARMETHODV_ENTRY(env, cls, (uintptr_t)methodID),
1942                         HOTSPOT_JNI_CALLSTATICCHARMETHODV_RETURN(_ret_ref));
1943 DEFINE_CALLSTATICMETHODV(jshort,   Short,   T_SHORT
1944                         , HOTSPOT_JNI_CALLSTATICSHORTMETHODV_ENTRY(env, cls, (uintptr_t)methodID),
1945                         HOTSPOT_JNI_CALLSTATICSHORTMETHODV_RETURN(_ret_ref));
1946 
1947 DEFINE_CALLSTATICMETHODV(jobject,  Object,  T_OBJECT
1948                         , HOTSPOT_JNI_CALLSTATICOBJECTMETHODV_ENTRY(env, cls, (uintptr_t)methodID),
1949                         HOTSPOT_JNI_CALLSTATICOBJECTMETHODV_RETURN(_ret_ref));
1950 DEFINE_CALLSTATICMETHODV(jint,     Int,     T_INT
1951                         , HOTSPOT_JNI_CALLSTATICINTMETHODV_ENTRY(env, cls, (uintptr_t)methodID),
1952                         HOTSPOT_JNI_CALLSTATICINTMETHODV_RETURN(_ret_ref));
1953 DEFINE_CALLSTATICMETHODV(jlong,    Long,    T_LONG
1954                         , HOTSPOT_JNI_CALLSTATICLONGMETHODV_ENTRY(env, cls, (uintptr_t)methodID),
1955                         HOTSPOT_JNI_CALLSTATICLONGMETHODV_RETURN(_ret_ref));
1956 // Float and double probes don't return value because dtrace doesn't currently support it
1957 DEFINE_CALLSTATICMETHODV(jfloat,   Float,   T_FLOAT
1958                         , HOTSPOT_JNI_CALLSTATICFLOATMETHODV_ENTRY(env, cls, (uintptr_t)methodID),
1959                         HOTSPOT_JNI_CALLSTATICFLOATMETHODV_RETURN());
1960 DEFINE_CALLSTATICMETHODV(jdouble,  Double,  T_DOUBLE
1961                         , HOTSPOT_JNI_CALLSTATICDOUBLEMETHODV_ENTRY(env, cls, (uintptr_t)methodID),
1962                         HOTSPOT_JNI_CALLSTATICDOUBLEMETHODV_RETURN());
1963 
1964 #define DEFINE_CALLSTATICMETHODA(ResultType, Result, Tag \
1965                                 , EntryProbe, ResultProbe) \
1966 \
1967   DT_RETURN_MARK_DECL_FOR(Result, CallStatic##Result##MethodA, ResultType \
1968                           , ResultProbe);                               \
1969 \
1970 JNI_ENTRY(ResultType, \
1971           jni_CallStatic##Result##MethodA(JNIEnv *env, jclass cls, jmethodID methodID, const jvalue *args)) \
1972   JNIWrapper("CallStatic" XSTR(Result) "MethodA"); \
1973 \
1974   EntryProbe; \
1975   ResultType ret = 0;\
1976   DT_RETURN_MARK_FOR(Result, CallStatic##Result##MethodA, ResultType, \
1977                      (const ResultType&)ret);\
1978 \
1979   JavaValue jvalue(Tag); \
1980   JNI_ArgumentPusherArray ap(methodID, args); \
1981   jni_invoke_static(env, &jvalue, NULL, JNI_STATIC, methodID, &ap, CHECK_0); \
1982   ret = jvalue.get_##ResultType(); \
1983   return ret;\
1984 JNI_END
1985 
1986 // the runtime type of subword integral basic types is integer
1987 DEFINE_CALLSTATICMETHODA(jboolean, Boolean, T_BOOLEAN
1988                         , HOTSPOT_JNI_CALLSTATICBOOLEANMETHODA_ENTRY(env, cls, (uintptr_t)methodID),
1989                         HOTSPOT_JNI_CALLSTATICBOOLEANMETHODA_RETURN(_ret_ref));
1990 DEFINE_CALLSTATICMETHODA(jbyte,    Byte,    T_BYTE
1991                         , HOTSPOT_JNI_CALLSTATICBYTEMETHODA_ENTRY(env, cls, (uintptr_t)methodID),
1992                         HOTSPOT_JNI_CALLSTATICBYTEMETHODA_RETURN(_ret_ref));
1993 DEFINE_CALLSTATICMETHODA(jchar,    Char,    T_CHAR
1994                         , HOTSPOT_JNI_CALLSTATICCHARMETHODA_ENTRY(env, cls, (uintptr_t)methodID),
1995                         HOTSPOT_JNI_CALLSTATICCHARMETHODA_RETURN(_ret_ref));
1996 DEFINE_CALLSTATICMETHODA(jshort,   Short,   T_SHORT
1997                         , HOTSPOT_JNI_CALLSTATICSHORTMETHODA_ENTRY(env, cls, (uintptr_t)methodID),
1998                         HOTSPOT_JNI_CALLSTATICSHORTMETHODA_RETURN(_ret_ref));
1999 
2000 DEFINE_CALLSTATICMETHODA(jobject,  Object,  T_OBJECT
2001                         , HOTSPOT_JNI_CALLSTATICOBJECTMETHODA_ENTRY(env, cls, (uintptr_t)methodID),
2002                         HOTSPOT_JNI_CALLSTATICOBJECTMETHODA_RETURN(_ret_ref));
2003 DEFINE_CALLSTATICMETHODA(jint,     Int,     T_INT
2004                         , HOTSPOT_JNI_CALLSTATICINTMETHODA_ENTRY(env, cls, (uintptr_t)methodID),
2005                         HOTSPOT_JNI_CALLSTATICINTMETHODA_RETURN(_ret_ref));
2006 DEFINE_CALLSTATICMETHODA(jlong,    Long,    T_LONG
2007                         , HOTSPOT_JNI_CALLSTATICLONGMETHODA_ENTRY(env, cls, (uintptr_t)methodID),
2008                         HOTSPOT_JNI_CALLSTATICLONGMETHODA_RETURN(_ret_ref));
2009 // Float and double probes don't return value because dtrace doesn't currently support it
2010 DEFINE_CALLSTATICMETHODA(jfloat,   Float,   T_FLOAT
2011                         , HOTSPOT_JNI_CALLSTATICFLOATMETHODA_ENTRY(env, cls, (uintptr_t)methodID),
2012                         HOTSPOT_JNI_CALLSTATICFLOATMETHODA_RETURN());
2013 DEFINE_CALLSTATICMETHODA(jdouble,  Double,  T_DOUBLE
2014                         , HOTSPOT_JNI_CALLSTATICDOUBLEMETHODA_ENTRY(env, cls, (uintptr_t)methodID),
2015                         HOTSPOT_JNI_CALLSTATICDOUBLEMETHODA_RETURN());
2016 
2017 DT_VOID_RETURN_MARK_DECL(CallStaticVoidMethod
2018                          , HOTSPOT_JNI_CALLSTATICVOIDMETHOD_RETURN());
2019 DT_VOID_RETURN_MARK_DECL(CallStaticVoidMethodV
2020                          , HOTSPOT_JNI_CALLSTATICVOIDMETHODV_RETURN());
2021 DT_VOID_RETURN_MARK_DECL(CallStaticVoidMethodA
2022                          , HOTSPOT_JNI_CALLSTATICVOIDMETHODA_RETURN());
2023 
2024 JNI_ENTRY(void, jni_CallStaticVoidMethod(JNIEnv *env, jclass cls, jmethodID methodID, ...))
2025   JNIWrapper("CallStaticVoidMethod");
2026   HOTSPOT_JNI_CALLSTATICVOIDMETHOD_ENTRY(env, cls, (uintptr_t) methodID);
2027   DT_VOID_RETURN_MARK(CallStaticVoidMethod);
2028 
2029   va_list args;
2030   va_start(args, methodID);
2031   JavaValue jvalue(T_VOID);
2032   JNI_ArgumentPusherVaArg ap(methodID, args);
2033   jni_invoke_static(env, &jvalue, NULL, JNI_STATIC, methodID, &ap, CHECK);
2034   va_end(args);
2035 JNI_END
2036 
2037 
2038 JNI_ENTRY(void, jni_CallStaticVoidMethodV(JNIEnv *env, jclass cls, jmethodID methodID, va_list args))
2039   JNIWrapper("CallStaticVoidMethodV");
2040   HOTSPOT_JNI_CALLSTATICVOIDMETHODV_ENTRY(env, cls, (uintptr_t) methodID);
2041   DT_VOID_RETURN_MARK(CallStaticVoidMethodV);
2042 
2043   JavaValue jvalue(T_VOID);
2044   JNI_ArgumentPusherVaArg ap(methodID, args);
2045   jni_invoke_static(env, &jvalue, NULL, JNI_STATIC, methodID, &ap, CHECK);
2046 JNI_END
2047 
2048 
2049 JNI_ENTRY(void, jni_CallStaticVoidMethodA(JNIEnv *env, jclass cls, jmethodID methodID, const jvalue *args))
2050   JNIWrapper("CallStaticVoidMethodA");
2051   HOTSPOT_JNI_CALLSTATICVOIDMETHODA_ENTRY(env, cls, (uintptr_t) methodID);
2052   DT_VOID_RETURN_MARK(CallStaticVoidMethodA);
2053 
2054   JavaValue jvalue(T_VOID);
2055   JNI_ArgumentPusherArray ap(methodID, args);
2056   jni_invoke_static(env, &jvalue, NULL, JNI_STATIC, methodID, &ap, CHECK);
2057 JNI_END
2058 
2059 
2060 //
2061 // Accessing Fields
2062 //
2063 
2064 
2065 DT_RETURN_MARK_DECL(GetFieldID, jfieldID
2066                     , HOTSPOT_JNI_GETFIELDID_RETURN((uintptr_t)_ret_ref));
2067 
2068 JNI_ENTRY(jfieldID, jni_GetFieldID(JNIEnv *env, jclass clazz,
2069           const char *name, const char *sig))
2070   JNIWrapper("GetFieldID");
2071   HOTSPOT_JNI_GETFIELDID_ENTRY(env, clazz, (char *) name, (char *) sig);
2072   jfieldID ret = 0;
2073   DT_RETURN_MARK(GetFieldID, jfieldID, (const jfieldID&)ret);
2074 
2075   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(clazz));
2076 
2077   // The class should have been loaded (we have an instance of the class
2078   // passed in) so the field and signature should already be in the symbol
2079   // table.  If they're not there, the field doesn't exist.
2080   TempNewSymbol fieldname = SymbolTable::probe(name, (int)strlen(name));
2081   TempNewSymbol signame = SymbolTable::probe(sig, (int)strlen(sig));
2082   if (fieldname == NULL || signame == NULL) {
2083     ResourceMark rm;
2084     THROW_MSG_0(vmSymbols::java_lang_NoSuchFieldError(), err_msg("%s.%s %s", k->external_name(), name, sig));
2085   }
2086 
2087   // Make sure class is initialized before handing id's out to fields
2088   k->initialize(CHECK_NULL);
2089 
2090   fieldDescriptor fd;
2091   if (!k->is_instance_klass() ||
2092       !InstanceKlass::cast(k)->find_field(fieldname, signame, false, &fd)) {
2093     ResourceMark rm;
2094     THROW_MSG_0(vmSymbols::java_lang_NoSuchFieldError(), err_msg("%s.%s %s", k->external_name(), name, sig));
2095   }
2096 
2097   // A jfieldID for a non-static field is simply the offset of the field within the instanceOop
2098   // It may also have hash bits for k, if VerifyJNIFields is turned on.
2099   ret = jfieldIDWorkaround::to_instance_jfieldID(k, fd.offset(), fd.is_flattened());
2100   return ret;
2101 JNI_END
2102 
2103 
2104 JNI_ENTRY(jobject, jni_GetObjectField(JNIEnv *env, jobject obj, jfieldID fieldID))
2105   JNIWrapper("GetObjectField");
2106   HOTSPOT_JNI_GETOBJECTFIELD_ENTRY(env, obj, (uintptr_t) fieldID);
2107   oop o = JNIHandles::resolve_non_null(obj);
2108   Klass* k = o->klass();
2109   int offset = jfieldIDWorkaround::from_instance_jfieldID(k, fieldID);
2110   oop res = NULL;
2111   // Keep JVMTI addition small and only check enabled flag here.
2112   // jni_GetField_probe() assumes that is okay to create handles.
2113   if (JvmtiExport::should_post_field_access()) {
2114     o = JvmtiExport::jni_GetField_probe(thread, obj, o, k, fieldID, false);
2115   }
2116   if (!jfieldIDWorkaround::is_flattened_field(fieldID)) {
2117     res = HeapAccess<ON_UNKNOWN_OOP_REF>::oop_load_at(o, offset);
2118   } else {
2119     assert(k->is_instance_klass(), "Only instance can have flattened fields");
2120     InstanceKlass* ik = InstanceKlass::cast(k);
2121     fieldDescriptor fd;
2122     ik->find_field_from_offset(offset, false, &fd);  // performance bottleneck
2123     InstanceKlass* holder = fd.field_holder();
2124     ValueKlass* field_vklass = ValueKlass::cast(holder->get_value_field_klass(fd.index()));
2125     res = field_vklass->read_flattened_field(o, ik->field_offset(fd.index()), CHECK_NULL);
2126   }
2127   jobject ret = JNIHandles::make_local(env, res);
2128   HOTSPOT_JNI_GETOBJECTFIELD_RETURN(ret);
2129   return ret;
2130 JNI_END
2131 
2132 
2133 
2134 #define DEFINE_GETFIELD(Return,Fieldname,Result \
2135   , EntryProbe, ReturnProbe) \
2136 \
2137   DT_RETURN_MARK_DECL_FOR(Result, Get##Result##Field, Return \
2138   , ReturnProbe); \
2139 \
2140 JNI_ENTRY_NO_PRESERVE(Return, jni_Get##Result##Field(JNIEnv *env, jobject obj, jfieldID fieldID)) \
2141   JNIWrapper("Get" XSTR(Result) "Field"); \
2142 \
2143   EntryProbe; \
2144   Return ret = 0;\
2145   DT_RETURN_MARK_FOR(Result, Get##Result##Field, Return, (const Return&)ret);\
2146 \
2147   oop o = JNIHandles::resolve_non_null(obj); \
2148   Klass* k = o->klass(); \
2149   int offset = jfieldIDWorkaround::from_instance_jfieldID(k, fieldID);  \
2150   /* Keep JVMTI addition small and only check enabled flag here.       */ \
2151   /* jni_GetField_probe_nh() assumes that is not okay to create handles */ \
2152   /* and creates a ResetNoHandleMark.                                   */ \
2153   if (JvmtiExport::should_post_field_access()) { \
2154     o = JvmtiExport::jni_GetField_probe_nh(thread, obj, o, k, fieldID, false); \
2155   } \
2156   ret = o->Fieldname##_field(offset); \
2157   return ret; \
2158 JNI_END
2159 
2160 DEFINE_GETFIELD(jboolean, bool,   Boolean
2161                 , HOTSPOT_JNI_GETBOOLEANFIELD_ENTRY(env, obj, (uintptr_t)fieldID),
2162                 HOTSPOT_JNI_GETBOOLEANFIELD_RETURN(_ret_ref))
2163 DEFINE_GETFIELD(jbyte,    byte,   Byte
2164                 , HOTSPOT_JNI_GETBYTEFIELD_ENTRY(env, obj, (uintptr_t)fieldID),
2165                 HOTSPOT_JNI_GETBYTEFIELD_RETURN(_ret_ref))
2166 DEFINE_GETFIELD(jchar,    char,   Char
2167                 , HOTSPOT_JNI_GETCHARFIELD_ENTRY(env, obj, (uintptr_t)fieldID),
2168                 HOTSPOT_JNI_GETCHARFIELD_RETURN(_ret_ref))
2169 DEFINE_GETFIELD(jshort,   short,  Short
2170                 , HOTSPOT_JNI_GETSHORTFIELD_ENTRY(env, obj, (uintptr_t)fieldID),
2171                 HOTSPOT_JNI_GETSHORTFIELD_RETURN(_ret_ref))
2172 DEFINE_GETFIELD(jint,     int,    Int
2173                 , HOTSPOT_JNI_GETINTFIELD_ENTRY(env, obj, (uintptr_t)fieldID),
2174                 HOTSPOT_JNI_GETINTFIELD_RETURN(_ret_ref))
2175 DEFINE_GETFIELD(jlong,    long,   Long
2176                 , HOTSPOT_JNI_GETLONGFIELD_ENTRY(env, obj, (uintptr_t)fieldID),
2177                 HOTSPOT_JNI_GETLONGFIELD_RETURN(_ret_ref))
2178 // Float and double probes don't return value because dtrace doesn't currently support it
2179 DEFINE_GETFIELD(jfloat,   float,  Float
2180                 , HOTSPOT_JNI_GETFLOATFIELD_ENTRY(env, obj, (uintptr_t)fieldID),
2181                 HOTSPOT_JNI_GETFLOATFIELD_RETURN())
2182 DEFINE_GETFIELD(jdouble,  double, Double
2183                 , HOTSPOT_JNI_GETDOUBLEFIELD_ENTRY(env, obj, (uintptr_t)fieldID),
2184                 HOTSPOT_JNI_GETDOUBLEFIELD_RETURN())
2185 
2186 address jni_GetBooleanField_addr() {
2187   return (address)jni_GetBooleanField;
2188 }
2189 address jni_GetByteField_addr() {
2190   return (address)jni_GetByteField;
2191 }
2192 address jni_GetCharField_addr() {
2193   return (address)jni_GetCharField;
2194 }
2195 address jni_GetShortField_addr() {
2196   return (address)jni_GetShortField;
2197 }
2198 address jni_GetIntField_addr() {
2199   return (address)jni_GetIntField;
2200 }
2201 address jni_GetLongField_addr() {
2202   return (address)jni_GetLongField;
2203 }
2204 address jni_GetFloatField_addr() {
2205   return (address)jni_GetFloatField;
2206 }
2207 address jni_GetDoubleField_addr() {
2208   return (address)jni_GetDoubleField;
2209 }
2210 
2211 JNI_ENTRY_NO_PRESERVE(void, jni_SetObjectField(JNIEnv *env, jobject obj, jfieldID fieldID, jobject value))
2212   JNIWrapper("SetObjectField");
2213   HOTSPOT_JNI_SETOBJECTFIELD_ENTRY(env, obj, (uintptr_t) fieldID, value);
2214   oop o = JNIHandles::resolve_non_null(obj);
2215   Klass* k = o->klass();
2216   int offset = jfieldIDWorkaround::from_instance_jfieldID(k, fieldID);
2217   // Keep JVMTI addition small and only check enabled flag here.
2218   // jni_SetField_probe_nh() assumes that is not okay to create handles
2219   // and creates a ResetNoHandleMark.
2220   if (JvmtiExport::should_post_field_modification()) {
2221     jvalue field_value;
2222     field_value.l = value;
2223     o = JvmtiExport::jni_SetField_probe_nh(thread, obj, o, k, fieldID, false, JVM_SIGNATURE_CLASS, (jvalue *)&field_value);
2224   }
2225   if (!jfieldIDWorkaround::is_flattened_field(fieldID)) {
2226     HeapAccess<ON_UNKNOWN_OOP_REF>::oop_store_at(o, offset, JNIHandles::resolve(value));
2227   } else {
2228     assert(k->is_instance_klass(), "Only instances can have flattened fields");
2229     InstanceKlass* ik = InstanceKlass::cast(k);
2230     fieldDescriptor fd;
2231     ik->find_field_from_offset(offset, false, &fd);
2232     InstanceKlass* holder = fd.field_holder();
2233     ValueKlass* vklass = ValueKlass::cast(holder->get_value_field_klass(fd.index()));
2234     oop v = JNIHandles::resolve_non_null(value);
2235     vklass->write_flattened_field(o, offset, v, CHECK);
2236   }
2237   HOTSPOT_JNI_SETOBJECTFIELD_RETURN();
2238 JNI_END
2239 
2240 
2241 #define DEFINE_SETFIELD(Argument,Fieldname,Result,SigType,unionType \
2242                         , EntryProbe, ReturnProbe) \
2243 \
2244 JNI_ENTRY_NO_PRESERVE(void, jni_Set##Result##Field(JNIEnv *env, jobject obj, jfieldID fieldID, Argument value)) \
2245   JNIWrapper("Set" XSTR(Result) "Field"); \
2246 \
2247   EntryProbe; \
2248 \
2249   oop o = JNIHandles::resolve_non_null(obj); \
2250   Klass* k = o->klass(); \
2251   int offset = jfieldIDWorkaround::from_instance_jfieldID(k, fieldID);  \
2252   /* Keep JVMTI addition small and only check enabled flag here.       */ \
2253   /* jni_SetField_probe_nh() assumes that is not okay to create handles */ \
2254   /* and creates a ResetNoHandleMark.                                   */ \
2255   if (JvmtiExport::should_post_field_modification()) { \
2256     jvalue field_value; \
2257     field_value.unionType = value; \
2258     o = JvmtiExport::jni_SetField_probe_nh(thread, obj, o, k, fieldID, false, SigType, (jvalue *)&field_value); \
2259   } \
2260   if (SigType == JVM_SIGNATURE_BOOLEAN) { value = ((jboolean)value) & 1; } \
2261   o->Fieldname##_field_put(offset, value); \
2262   ReturnProbe; \
2263 JNI_END
2264 
2265 DEFINE_SETFIELD(jboolean, bool,   Boolean, JVM_SIGNATURE_BOOLEAN, z
2266                 , HOTSPOT_JNI_SETBOOLEANFIELD_ENTRY(env, obj, (uintptr_t)fieldID, value),
2267                 HOTSPOT_JNI_SETBOOLEANFIELD_RETURN())
2268 DEFINE_SETFIELD(jbyte,    byte,   Byte,    JVM_SIGNATURE_BYTE, b
2269                 , HOTSPOT_JNI_SETBYTEFIELD_ENTRY(env, obj, (uintptr_t)fieldID, value),
2270                 HOTSPOT_JNI_SETBYTEFIELD_RETURN())
2271 DEFINE_SETFIELD(jchar,    char,   Char,    JVM_SIGNATURE_CHAR, c
2272                 , HOTSPOT_JNI_SETCHARFIELD_ENTRY(env, obj, (uintptr_t)fieldID, value),
2273                 HOTSPOT_JNI_SETCHARFIELD_RETURN())
2274 DEFINE_SETFIELD(jshort,   short,  Short,   JVM_SIGNATURE_SHORT, s
2275                 , HOTSPOT_JNI_SETSHORTFIELD_ENTRY(env, obj, (uintptr_t)fieldID, value),
2276                 HOTSPOT_JNI_SETSHORTFIELD_RETURN())
2277 DEFINE_SETFIELD(jint,     int,    Int,     JVM_SIGNATURE_INT, i
2278                 , HOTSPOT_JNI_SETINTFIELD_ENTRY(env, obj, (uintptr_t)fieldID, value),
2279                 HOTSPOT_JNI_SETINTFIELD_RETURN())
2280 DEFINE_SETFIELD(jlong,    long,   Long,    JVM_SIGNATURE_LONG, j
2281                 , HOTSPOT_JNI_SETLONGFIELD_ENTRY(env, obj, (uintptr_t)fieldID, value),
2282                 HOTSPOT_JNI_SETLONGFIELD_RETURN())
2283 // Float and double probes don't return value because dtrace doesn't currently support it
2284 DEFINE_SETFIELD(jfloat,   float,  Float,   JVM_SIGNATURE_FLOAT, f
2285                 , HOTSPOT_JNI_SETFLOATFIELD_ENTRY(env, obj, (uintptr_t)fieldID),
2286                 HOTSPOT_JNI_SETFLOATFIELD_RETURN())
2287 DEFINE_SETFIELD(jdouble,  double, Double,  JVM_SIGNATURE_DOUBLE, d
2288                 , HOTSPOT_JNI_SETDOUBLEFIELD_ENTRY(env, obj, (uintptr_t)fieldID),
2289                 HOTSPOT_JNI_SETDOUBLEFIELD_RETURN())
2290 
2291 DT_RETURN_MARK_DECL(ToReflectedField, jobject
2292                     , HOTSPOT_JNI_TOREFLECTEDFIELD_RETURN(_ret_ref));
2293 
2294 JNI_ENTRY(jobject, jni_ToReflectedField(JNIEnv *env, jclass cls, jfieldID fieldID, jboolean isStatic))
2295   JNIWrapper("ToReflectedField");
2296   HOTSPOT_JNI_TOREFLECTEDFIELD_ENTRY(env, cls, (uintptr_t) fieldID, isStatic);
2297   jobject ret = NULL;
2298   DT_RETURN_MARK(ToReflectedField, jobject, (const jobject&)ret);
2299 
2300   fieldDescriptor fd;
2301   bool found = false;
2302   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2303 
2304   assert(jfieldIDWorkaround::is_static_jfieldID(fieldID) == (isStatic != 0), "invalid fieldID");
2305 
2306   if (isStatic) {
2307     // Static field. The fieldID a JNIid specifying the field holder and the offset within the Klass*.
2308     JNIid* id = jfieldIDWorkaround::from_static_jfieldID(fieldID);
2309     assert(id->is_static_field_id(), "invalid static field id");
2310     found = id->find_local_field(&fd);
2311   } else {
2312     // Non-static field. The fieldID is really the offset of the field within the instanceOop.
2313     int offset = jfieldIDWorkaround::from_instance_jfieldID(k, fieldID);
2314     found = InstanceKlass::cast(k)->find_field_from_offset(offset, false, &fd);
2315   }
2316   assert(found, "bad fieldID passed into jni_ToReflectedField");
2317   oop reflected = Reflection::new_field(&fd, CHECK_NULL);
2318   ret = JNIHandles::make_local(env, reflected);
2319   return ret;
2320 JNI_END
2321 
2322 
2323 //
2324 // Accessing Static Fields
2325 //
2326 DT_RETURN_MARK_DECL(GetStaticFieldID, jfieldID
2327                     , HOTSPOT_JNI_GETSTATICFIELDID_RETURN((uintptr_t)_ret_ref));
2328 
2329 JNI_ENTRY(jfieldID, jni_GetStaticFieldID(JNIEnv *env, jclass clazz,
2330           const char *name, const char *sig))
2331   JNIWrapper("GetStaticFieldID");
2332   HOTSPOT_JNI_GETSTATICFIELDID_ENTRY(env, clazz, (char *) name, (char *) sig);
2333   jfieldID ret = NULL;
2334   DT_RETURN_MARK(GetStaticFieldID, jfieldID, (const jfieldID&)ret);
2335 
2336   // The class should have been loaded (we have an instance of the class
2337   // passed in) so the field and signature should already be in the symbol
2338   // table.  If they're not there, the field doesn't exist.
2339   TempNewSymbol fieldname = SymbolTable::probe(name, (int)strlen(name));
2340   TempNewSymbol signame = SymbolTable::probe(sig, (int)strlen(sig));
2341   if (fieldname == NULL || signame == NULL) {
2342     THROW_MSG_0(vmSymbols::java_lang_NoSuchFieldError(), (char*) name);
2343   }
2344   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(clazz));
2345   // Make sure class is initialized before handing id's out to static fields
2346   k->initialize(CHECK_NULL);
2347 
2348   fieldDescriptor fd;
2349   if (!k->is_instance_klass() ||
2350       !InstanceKlass::cast(k)->find_field(fieldname, signame, true, &fd)) {
2351     THROW_MSG_0(vmSymbols::java_lang_NoSuchFieldError(), (char*) name);
2352   }
2353 
2354   // A jfieldID for a static field is a JNIid specifying the field holder and the offset within the Klass*
2355   JNIid* id = fd.field_holder()->jni_id_for(fd.offset());
2356   debug_only(id->set_is_static_field_id();)
2357 
2358   debug_only(id->verify(fd.field_holder()));
2359 
2360   ret = jfieldIDWorkaround::to_static_jfieldID(id);
2361   return ret;
2362 JNI_END
2363 
2364 
2365 JNI_ENTRY(jobject, jni_GetStaticObjectField(JNIEnv *env, jclass clazz, jfieldID fieldID))
2366   JNIWrapper("GetStaticObjectField");
2367   HOTSPOT_JNI_GETSTATICOBJECTFIELD_ENTRY(env, clazz, (uintptr_t) fieldID);
2368 #if INCLUDE_JNI_CHECK
2369   DEBUG_ONLY(Klass* param_k = jniCheck::validate_class(thread, clazz);)
2370 #endif // INCLUDE_JNI_CHECK
2371   JNIid* id = jfieldIDWorkaround::from_static_jfieldID(fieldID);
2372   assert(id->is_static_field_id(), "invalid static field id");
2373   // Keep JVMTI addition small and only check enabled flag here.
2374   // jni_GetField_probe() assumes that is okay to create handles.
2375   if (JvmtiExport::should_post_field_access()) {
2376     JvmtiExport::jni_GetField_probe(thread, NULL, NULL, id->holder(), fieldID, true);
2377   }
2378   jobject ret = JNIHandles::make_local(id->holder()->java_mirror()->obj_field(id->offset()));
2379   HOTSPOT_JNI_GETSTATICOBJECTFIELD_RETURN(ret);
2380   return ret;
2381 JNI_END
2382 
2383 
2384 #define DEFINE_GETSTATICFIELD(Return,Fieldname,Result \
2385                               , EntryProbe, ReturnProbe) \
2386 \
2387   DT_RETURN_MARK_DECL_FOR(Result, GetStatic##Result##Field, Return \
2388                           , ReturnProbe);                                          \
2389 \
2390 JNI_ENTRY(Return, jni_GetStatic##Result##Field(JNIEnv *env, jclass clazz, jfieldID fieldID)) \
2391   JNIWrapper("GetStatic" XSTR(Result) "Field"); \
2392   EntryProbe; \
2393   Return ret = 0;\
2394   DT_RETURN_MARK_FOR(Result, GetStatic##Result##Field, Return, \
2395                      (const Return&)ret);\
2396   JNIid* id = jfieldIDWorkaround::from_static_jfieldID(fieldID); \
2397   assert(id->is_static_field_id(), "invalid static field id"); \
2398   /* Keep JVMTI addition small and only check enabled flag here. */ \
2399   /* jni_GetField_probe() assumes that is okay to create handles. */ \
2400   if (JvmtiExport::should_post_field_access()) { \
2401     JvmtiExport::jni_GetField_probe(thread, NULL, NULL, id->holder(), fieldID, true); \
2402   } \
2403   ret = id->holder()->java_mirror()-> Fieldname##_field (id->offset()); \
2404   return ret;\
2405 JNI_END
2406 
2407 DEFINE_GETSTATICFIELD(jboolean, bool,   Boolean
2408                       , HOTSPOT_JNI_GETSTATICBOOLEANFIELD_ENTRY(env, clazz, (uintptr_t) fieldID), HOTSPOT_JNI_GETSTATICBOOLEANFIELD_RETURN(_ret_ref))
2409 DEFINE_GETSTATICFIELD(jbyte,    byte,   Byte
2410                       , HOTSPOT_JNI_GETSTATICBYTEFIELD_ENTRY(env, clazz, (uintptr_t) fieldID),    HOTSPOT_JNI_GETSTATICBYTEFIELD_RETURN(_ret_ref)   )
2411 DEFINE_GETSTATICFIELD(jchar,    char,   Char
2412                       , HOTSPOT_JNI_GETSTATICCHARFIELD_ENTRY(env, clazz, (uintptr_t) fieldID),    HOTSPOT_JNI_GETSTATICCHARFIELD_RETURN(_ret_ref)   )
2413 DEFINE_GETSTATICFIELD(jshort,   short,  Short
2414                       , HOTSPOT_JNI_GETSTATICSHORTFIELD_ENTRY(env, clazz, (uintptr_t) fieldID),   HOTSPOT_JNI_GETSTATICSHORTFIELD_RETURN(_ret_ref)  )
2415 DEFINE_GETSTATICFIELD(jint,     int,    Int
2416                       , HOTSPOT_JNI_GETSTATICINTFIELD_ENTRY(env, clazz, (uintptr_t) fieldID),     HOTSPOT_JNI_GETSTATICINTFIELD_RETURN(_ret_ref)    )
2417 DEFINE_GETSTATICFIELD(jlong,    long,   Long
2418                       , HOTSPOT_JNI_GETSTATICLONGFIELD_ENTRY(env, clazz, (uintptr_t) fieldID),    HOTSPOT_JNI_GETSTATICLONGFIELD_RETURN(_ret_ref)   )
2419 // Float and double probes don't return value because dtrace doesn't currently support it
2420 DEFINE_GETSTATICFIELD(jfloat,   float,  Float
2421                       , HOTSPOT_JNI_GETSTATICFLOATFIELD_ENTRY(env, clazz, (uintptr_t) fieldID),   HOTSPOT_JNI_GETSTATICFLOATFIELD_RETURN()          )
2422 DEFINE_GETSTATICFIELD(jdouble,  double, Double
2423                       , HOTSPOT_JNI_GETSTATICDOUBLEFIELD_ENTRY(env, clazz, (uintptr_t) fieldID),  HOTSPOT_JNI_GETSTATICDOUBLEFIELD_RETURN()         )
2424 
2425 JNI_ENTRY(void, jni_SetStaticObjectField(JNIEnv *env, jclass clazz, jfieldID fieldID, jobject value))
2426   JNIWrapper("SetStaticObjectField");
2427  HOTSPOT_JNI_SETSTATICOBJECTFIELD_ENTRY(env, clazz, (uintptr_t) fieldID, value);
2428   JNIid* id = jfieldIDWorkaround::from_static_jfieldID(fieldID);
2429   assert(id->is_static_field_id(), "invalid static field id");
2430   // Keep JVMTI addition small and only check enabled flag here.
2431   // jni_SetField_probe() assumes that is okay to create handles.
2432   if (JvmtiExport::should_post_field_modification()) {
2433     jvalue field_value;
2434     field_value.l = value;
2435     JvmtiExport::jni_SetField_probe(thread, NULL, NULL, id->holder(), fieldID, true, JVM_SIGNATURE_CLASS, (jvalue *)&field_value);
2436   }
2437   id->holder()->java_mirror()->obj_field_put(id->offset(), JNIHandles::resolve(value));
2438   HOTSPOT_JNI_SETSTATICOBJECTFIELD_RETURN();
2439 JNI_END
2440 
2441 
2442 
2443 #define DEFINE_SETSTATICFIELD(Argument,Fieldname,Result,SigType,unionType \
2444                               , EntryProbe, ReturnProbe) \
2445 \
2446 JNI_ENTRY(void, jni_SetStatic##Result##Field(JNIEnv *env, jclass clazz, jfieldID fieldID, Argument value)) \
2447   JNIWrapper("SetStatic" XSTR(Result) "Field"); \
2448   EntryProbe; \
2449 \
2450   JNIid* id = jfieldIDWorkaround::from_static_jfieldID(fieldID); \
2451   assert(id->is_static_field_id(), "invalid static field id"); \
2452   /* Keep JVMTI addition small and only check enabled flag here. */ \
2453   /* jni_SetField_probe() assumes that is okay to create handles. */ \
2454   if (JvmtiExport::should_post_field_modification()) { \
2455     jvalue field_value; \
2456     field_value.unionType = value; \
2457     JvmtiExport::jni_SetField_probe(thread, NULL, NULL, id->holder(), fieldID, true, SigType, (jvalue *)&field_value); \
2458   } \
2459   if (SigType == JVM_SIGNATURE_BOOLEAN) { value = ((jboolean)value) & 1; } \
2460   id->holder()->java_mirror()-> Fieldname##_field_put (id->offset(), value); \
2461   ReturnProbe;\
2462 JNI_END
2463 
2464 DEFINE_SETSTATICFIELD(jboolean, bool,   Boolean, JVM_SIGNATURE_BOOLEAN, z
2465                       , HOTSPOT_JNI_SETSTATICBOOLEANFIELD_ENTRY(env, clazz, (uintptr_t)fieldID, value),
2466                       HOTSPOT_JNI_SETSTATICBOOLEANFIELD_RETURN())
2467 DEFINE_SETSTATICFIELD(jbyte,    byte,   Byte,    JVM_SIGNATURE_BYTE, b
2468                       , HOTSPOT_JNI_SETSTATICBYTEFIELD_ENTRY(env, clazz, (uintptr_t) fieldID, value),
2469                       HOTSPOT_JNI_SETSTATICBYTEFIELD_RETURN())
2470 DEFINE_SETSTATICFIELD(jchar,    char,   Char,    JVM_SIGNATURE_CHAR, c
2471                       , HOTSPOT_JNI_SETSTATICCHARFIELD_ENTRY(env, clazz, (uintptr_t) fieldID, value),
2472                       HOTSPOT_JNI_SETSTATICCHARFIELD_RETURN())
2473 DEFINE_SETSTATICFIELD(jshort,   short,  Short,   JVM_SIGNATURE_SHORT, s
2474                       , HOTSPOT_JNI_SETSTATICSHORTFIELD_ENTRY(env, clazz, (uintptr_t) fieldID, value),
2475                       HOTSPOT_JNI_SETSTATICSHORTFIELD_RETURN())
2476 DEFINE_SETSTATICFIELD(jint,     int,    Int,     JVM_SIGNATURE_INT, i
2477                       , HOTSPOT_JNI_SETSTATICINTFIELD_ENTRY(env, clazz, (uintptr_t) fieldID, value),
2478                       HOTSPOT_JNI_SETSTATICINTFIELD_RETURN())
2479 DEFINE_SETSTATICFIELD(jlong,    long,   Long,    JVM_SIGNATURE_LONG, j
2480                       , HOTSPOT_JNI_SETSTATICLONGFIELD_ENTRY(env, clazz, (uintptr_t) fieldID, value),
2481                       HOTSPOT_JNI_SETSTATICLONGFIELD_RETURN())
2482 // Float and double probes don't return value because dtrace doesn't currently support it
2483 DEFINE_SETSTATICFIELD(jfloat,   float,  Float,   JVM_SIGNATURE_FLOAT, f
2484                       , HOTSPOT_JNI_SETSTATICFLOATFIELD_ENTRY(env, clazz, (uintptr_t) fieldID),
2485                       HOTSPOT_JNI_SETSTATICFLOATFIELD_RETURN())
2486 DEFINE_SETSTATICFIELD(jdouble,  double, Double,  JVM_SIGNATURE_DOUBLE, d
2487                       , HOTSPOT_JNI_SETSTATICDOUBLEFIELD_ENTRY(env, clazz, (uintptr_t) fieldID),
2488                       HOTSPOT_JNI_SETSTATICDOUBLEFIELD_RETURN())
2489 
2490 //
2491 // String Operations
2492 //
2493 
2494 // Unicode Interface
2495 
2496 DT_RETURN_MARK_DECL(NewString, jstring
2497                     , HOTSPOT_JNI_NEWSTRING_RETURN(_ret_ref));
2498 
2499 JNI_ENTRY(jstring, jni_NewString(JNIEnv *env, const jchar *unicodeChars, jsize len))
2500   JNIWrapper("NewString");
2501  HOTSPOT_JNI_NEWSTRING_ENTRY(env, (uint16_t *) unicodeChars, len);
2502   jstring ret = NULL;
2503   DT_RETURN_MARK(NewString, jstring, (const jstring&)ret);
2504   oop string=java_lang_String::create_oop_from_unicode((jchar*) unicodeChars, len, CHECK_NULL);
2505   ret = (jstring) JNIHandles::make_local(env, string);
2506   return ret;
2507 JNI_END
2508 
2509 
2510 JNI_ENTRY_NO_PRESERVE(jsize, jni_GetStringLength(JNIEnv *env, jstring string))
2511   JNIWrapper("GetStringLength");
2512   HOTSPOT_JNI_GETSTRINGLENGTH_ENTRY(env, string);
2513   jsize ret = 0;
2514   oop s = JNIHandles::resolve_non_null(string);
2515   ret = java_lang_String::length(s);
2516  HOTSPOT_JNI_GETSTRINGLENGTH_RETURN(ret);
2517   return ret;
2518 JNI_END
2519 
2520 
2521 JNI_ENTRY_NO_PRESERVE(const jchar*, jni_GetStringChars(
2522   JNIEnv *env, jstring string, jboolean *isCopy))
2523   JNIWrapper("GetStringChars");
2524  HOTSPOT_JNI_GETSTRINGCHARS_ENTRY(env, string, (uintptr_t *) isCopy);
2525   jchar* buf = NULL;
2526   oop s = JNIHandles::resolve_non_null(string);
2527   typeArrayOop s_value = java_lang_String::value(s);
2528   if (s_value != NULL) {
2529     int s_len = java_lang_String::length(s, s_value);
2530     bool is_latin1 = java_lang_String::is_latin1(s);
2531     buf = NEW_C_HEAP_ARRAY_RETURN_NULL(jchar, s_len + 1, mtInternal);  // add one for zero termination
2532     /* JNI Specification states return NULL on OOM */
2533     if (buf != NULL) {
2534       if (s_len > 0) {
2535         if (!is_latin1) {
2536           ArrayAccess<>::arraycopy_to_native(s_value, (size_t) typeArrayOopDesc::element_offset<jchar>(0),
2537                                              buf, s_len);
2538         } else {
2539           for (int i = 0; i < s_len; i++) {
2540             buf[i] = ((jchar) s_value->byte_at(i)) & 0xff;
2541           }
2542         }
2543       }
2544       buf[s_len] = 0;
2545       //%note jni_5
2546       if (isCopy != NULL) {
2547         *isCopy = JNI_TRUE;
2548       }
2549     }
2550   }
2551   HOTSPOT_JNI_GETSTRINGCHARS_RETURN(buf);
2552   return buf;
2553 JNI_END
2554 
2555 
2556 JNI_ENTRY_NO_PRESERVE(void, jni_ReleaseStringChars(JNIEnv *env, jstring str, const jchar *chars))
2557   JNIWrapper("ReleaseStringChars");
2558   HOTSPOT_JNI_RELEASESTRINGCHARS_ENTRY(env, str, (uint16_t *) chars);
2559   //%note jni_6
2560   if (chars != NULL) {
2561     // Since String objects are supposed to be immutable, don't copy any
2562     // new data back.  A bad user will have to go after the char array.
2563     FreeHeap((void*) chars);
2564   }
2565   HOTSPOT_JNI_RELEASESTRINGCHARS_RETURN();
2566 JNI_END
2567 
2568 
2569 // UTF Interface
2570 
2571 DT_RETURN_MARK_DECL(NewStringUTF, jstring
2572                     , HOTSPOT_JNI_NEWSTRINGUTF_RETURN(_ret_ref));
2573 
2574 JNI_ENTRY(jstring, jni_NewStringUTF(JNIEnv *env, const char *bytes))
2575   JNIWrapper("NewStringUTF");
2576   HOTSPOT_JNI_NEWSTRINGUTF_ENTRY(env, (char *) bytes);
2577   jstring ret;
2578   DT_RETURN_MARK(NewStringUTF, jstring, (const jstring&)ret);
2579 
2580   oop result = java_lang_String::create_oop_from_str((char*) bytes, CHECK_NULL);
2581   ret = (jstring) JNIHandles::make_local(env, result);
2582   return ret;
2583 JNI_END
2584 
2585 
2586 JNI_ENTRY(jsize, jni_GetStringUTFLength(JNIEnv *env, jstring string))
2587   JNIWrapper("GetStringUTFLength");
2588  HOTSPOT_JNI_GETSTRINGUTFLENGTH_ENTRY(env, string);
2589   oop java_string = JNIHandles::resolve_non_null(string);
2590   jsize ret = java_lang_String::utf8_length(java_string);
2591   HOTSPOT_JNI_GETSTRINGUTFLENGTH_RETURN(ret);
2592   return ret;
2593 JNI_END
2594 
2595 
2596 JNI_ENTRY(const char*, jni_GetStringUTFChars(JNIEnv *env, jstring string, jboolean *isCopy))
2597   JNIWrapper("GetStringUTFChars");
2598  HOTSPOT_JNI_GETSTRINGUTFCHARS_ENTRY(env, string, (uintptr_t *) isCopy);
2599   char* result = NULL;
2600   oop java_string = JNIHandles::resolve_non_null(string);
2601   typeArrayOop s_value = java_lang_String::value(java_string);
2602   if (s_value != NULL) {
2603     size_t length = java_lang_String::utf8_length(java_string, s_value);
2604     /* JNI Specification states return NULL on OOM */
2605     result = AllocateHeap(length + 1, mtInternal, 0, AllocFailStrategy::RETURN_NULL);
2606     if (result != NULL) {
2607       java_lang_String::as_utf8_string(java_string, s_value, result, (int) length + 1);
2608       if (isCopy != NULL) {
2609         *isCopy = JNI_TRUE;
2610       }
2611     }
2612   }
2613  HOTSPOT_JNI_GETSTRINGUTFCHARS_RETURN(result);
2614   return result;
2615 JNI_END
2616 
2617 
2618 JNI_LEAF(void, jni_ReleaseStringUTFChars(JNIEnv *env, jstring str, const char *chars))
2619   JNIWrapper("ReleaseStringUTFChars");
2620  HOTSPOT_JNI_RELEASESTRINGUTFCHARS_ENTRY(env, str, (char *) chars);
2621   if (chars != NULL) {
2622     FreeHeap((char*) chars);
2623   }
2624 HOTSPOT_JNI_RELEASESTRINGUTFCHARS_RETURN();
2625 JNI_END
2626 
2627 
2628 JNI_ENTRY_NO_PRESERVE(jsize, jni_GetArrayLength(JNIEnv *env, jarray array))
2629   JNIWrapper("GetArrayLength");
2630  HOTSPOT_JNI_GETARRAYLENGTH_ENTRY(env, array);
2631   arrayOop a = arrayOop(JNIHandles::resolve_non_null(array));
2632   assert(a->is_array(), "must be array");
2633   jsize ret = a->length();
2634  HOTSPOT_JNI_GETARRAYLENGTH_RETURN(ret);
2635   return ret;
2636 JNI_END
2637 
2638 
2639 //
2640 // Object Array Operations
2641 //
2642 
2643 DT_RETURN_MARK_DECL(NewObjectArray, jobjectArray
2644                     , HOTSPOT_JNI_NEWOBJECTARRAY_RETURN(_ret_ref));
2645 
2646 JNI_ENTRY(jobjectArray, jni_NewObjectArray(JNIEnv *env, jsize length, jclass elementClass, jobject initialElement))
2647   JNIWrapper("NewObjectArray");
2648  HOTSPOT_JNI_NEWOBJECTARRAY_ENTRY(env, length, elementClass, initialElement);
2649   jobjectArray ret = NULL;
2650   DT_RETURN_MARK(NewObjectArray, jobjectArray, (const jobjectArray&)ret);
2651   Klass* ek = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(elementClass));
2652   Klass* ak = ek->array_klass(CHECK_NULL);
2653   ObjArrayKlass::cast(ak)->initialize(CHECK_NULL);
2654   objArrayOop result = ObjArrayKlass::cast(ak)->allocate(length, CHECK_NULL);
2655   oop initial_value = JNIHandles::resolve(initialElement);
2656   if (initial_value != NULL) {  // array already initialized with NULL
2657     for (int index = 0; index < length; index++) {
2658       result->obj_at_put(index, initial_value);
2659     }
2660   }
2661   ret = (jobjectArray) JNIHandles::make_local(env, result);
2662   return ret;
2663 JNI_END
2664 
2665 DT_RETURN_MARK_DECL(GetObjectArrayElement, jobject
2666                     , HOTSPOT_JNI_GETOBJECTARRAYELEMENT_RETURN(_ret_ref));
2667 
2668 JNI_ENTRY(jobject, jni_GetObjectArrayElement(JNIEnv *env, jobjectArray array, jsize index))
2669   JNIWrapper("GetObjectArrayElement");
2670  HOTSPOT_JNI_GETOBJECTARRAYELEMENT_ENTRY(env, array, index);
2671   jobject ret = NULL;
2672   DT_RETURN_MARK(GetObjectArrayElement, jobject, (const jobject&)ret);
2673   oop res = NULL;
2674   arrayOop arr((arrayOop)JNIHandles::resolve_non_null(array));
2675   if (arr->is_within_bounds(index)) {
2676     if (arr->is_valueArray()) {
2677       valueArrayOop a = valueArrayOop(JNIHandles::resolve_non_null(array));
2678       arrayHandle ah(THREAD, a);
2679       valueArrayHandle vah(thread, a);
2680       res = valueArrayOopDesc::value_alloc_copy_from_index(vah, index, CHECK_NULL);
2681       assert(res != NULL, "Must be set in one of two paths above");
2682     } else {
2683       assert(arr->is_objArray(), "If not a valueArray. must be an objArray");
2684       objArrayOop a = objArrayOop(JNIHandles::resolve_non_null(array));
2685       res = a->obj_at(index);
2686     }
2687   } else {
2688     ResourceMark rm(THREAD);
2689     stringStream ss;
2690     ss.print("Index %d out of bounds for length %d", index,arr->length());
2691     THROW_MSG_0(vmSymbols::java_lang_ArrayIndexOutOfBoundsException(), ss.as_string());
2692   }
2693   ret = JNIHandles::make_local(env, res);
2694   return ret;
2695 JNI_END
2696 
2697 DT_VOID_RETURN_MARK_DECL(SetObjectArrayElement
2698                          , HOTSPOT_JNI_SETOBJECTARRAYELEMENT_RETURN());
2699 
2700 JNI_ENTRY(void, jni_SetObjectArrayElement(JNIEnv *env, jobjectArray array, jsize index, jobject value))
2701   JNIWrapper("SetObjectArrayElement");
2702   HOTSPOT_JNI_SETOBJECTARRAYELEMENT_ENTRY(env, array, index, value);
2703   DT_VOID_RETURN_MARK(SetObjectArrayElement);
2704 
2705    bool oob = false;
2706    int length = -1;
2707    oop res = NULL;
2708    arrayOop arr((arrayOop)JNIHandles::resolve_non_null(array));
2709    if (arr->is_within_bounds(index)) {
2710      if (arr->is_valueArray()) {
2711        valueArrayOop a = valueArrayOop(JNIHandles::resolve_non_null(array));
2712        oop v = JNIHandles::resolve(value);
2713        ValueArrayKlass* vaklass = ValueArrayKlass::cast(a->klass());
2714        ValueKlass* element_vklass = vaklass->element_klass();
2715        if (v != NULL && v->is_a(element_vklass)) {
2716          a->value_copy_to_index(v, index);
2717        } else {
2718          ResourceMark rm(THREAD);
2719          stringStream ss;
2720          Klass *kl = ValueArrayKlass::cast(a->klass());
2721          ss.print("type mismatch: can not store %s to %s[%d]",
2722              v->klass()->external_name(),
2723              kl->external_name(),
2724              index);
2725          for (int dims = ArrayKlass::cast(a->klass())->dimension(); dims > 1; --dims) {
2726            ss.print("[]");
2727          }
2728          THROW_MSG(vmSymbols::java_lang_ArrayStoreException(), ss.as_string());
2729        }
2730      } else {
2731        assert(arr->is_objArray(), "If not a valueArray. must be an objArray");
2732        objArrayOop a = objArrayOop(JNIHandles::resolve_non_null(array));
2733        oop v = JNIHandles::resolve(value);
2734        if (v == NULL || v->is_a(ObjArrayKlass::cast(a->klass())->element_klass())) {
2735          a->obj_at_put(index, v);
2736        } else {
2737          ResourceMark rm(THREAD);
2738          stringStream ss;
2739          Klass *bottom_kl = ObjArrayKlass::cast(a->klass())->bottom_klass();
2740          ss.print("type mismatch: can not store %s to %s[%d]",
2741              v->klass()->external_name(),
2742              bottom_kl->is_typeArray_klass() ? type2name_tab[ArrayKlass::cast(bottom_kl)->element_type()] : bottom_kl->external_name(),
2743                  index);
2744          for (int dims = ArrayKlass::cast(a->klass())->dimension(); dims > 1; --dims) {
2745            ss.print("[]");
2746          }
2747          THROW_MSG(vmSymbols::java_lang_ArrayStoreException(), ss.as_string());
2748        }
2749      }
2750    } else {
2751      ResourceMark rm(THREAD);
2752      stringStream ss;
2753      ss.print("Index %d out of bounds for length %d", index, arr->length());
2754      THROW_MSG(vmSymbols::java_lang_ArrayIndexOutOfBoundsException(), ss.as_string());
2755    }
2756 JNI_END
2757 
2758 
2759 
2760 #define DEFINE_NEWSCALARARRAY(Return,Allocator,Result \
2761                               ,EntryProbe,ReturnProbe)  \
2762 \
2763   DT_RETURN_MARK_DECL(New##Result##Array, Return \
2764                       , ReturnProbe); \
2765 \
2766 JNI_ENTRY(Return, \
2767           jni_New##Result##Array(JNIEnv *env, jsize len)) \
2768   JNIWrapper("New" XSTR(Result) "Array"); \
2769   EntryProbe; \
2770   Return ret = NULL;\
2771   DT_RETURN_MARK(New##Result##Array, Return, (const Return&)ret);\
2772 \
2773   oop obj= oopFactory::Allocator(len, CHECK_0); \
2774   ret = (Return) JNIHandles::make_local(env, obj); \
2775   return ret;\
2776 JNI_END
2777 
2778 DEFINE_NEWSCALARARRAY(jbooleanArray, new_boolArray,   Boolean,
2779                       HOTSPOT_JNI_NEWBOOLEANARRAY_ENTRY(env, len),
2780                       HOTSPOT_JNI_NEWBOOLEANARRAY_RETURN(_ret_ref))
2781 DEFINE_NEWSCALARARRAY(jbyteArray,    new_byteArray,   Byte,
2782                       HOTSPOT_JNI_NEWBYTEARRAY_ENTRY(env, len),
2783                       HOTSPOT_JNI_NEWBYTEARRAY_RETURN(_ret_ref))
2784 DEFINE_NEWSCALARARRAY(jshortArray,   new_shortArray,  Short,
2785                       HOTSPOT_JNI_NEWSHORTARRAY_ENTRY(env, len),
2786                       HOTSPOT_JNI_NEWSHORTARRAY_RETURN(_ret_ref))
2787 DEFINE_NEWSCALARARRAY(jcharArray,    new_charArray,   Char,
2788                       HOTSPOT_JNI_NEWCHARARRAY_ENTRY(env, len),
2789                       HOTSPOT_JNI_NEWCHARARRAY_RETURN(_ret_ref))
2790 DEFINE_NEWSCALARARRAY(jintArray,     new_intArray,    Int,
2791                       HOTSPOT_JNI_NEWINTARRAY_ENTRY(env, len),
2792                       HOTSPOT_JNI_NEWINTARRAY_RETURN(_ret_ref))
2793 DEFINE_NEWSCALARARRAY(jlongArray,    new_longArray,   Long,
2794                       HOTSPOT_JNI_NEWLONGARRAY_ENTRY(env, len),
2795                       HOTSPOT_JNI_NEWLONGARRAY_RETURN(_ret_ref))
2796 DEFINE_NEWSCALARARRAY(jfloatArray,   new_floatArray,  Float,
2797                       HOTSPOT_JNI_NEWFLOATARRAY_ENTRY(env, len),
2798                       HOTSPOT_JNI_NEWFLOATARRAY_RETURN(_ret_ref))
2799 DEFINE_NEWSCALARARRAY(jdoubleArray,  new_doubleArray, Double,
2800                       HOTSPOT_JNI_NEWDOUBLEARRAY_ENTRY(env, len),
2801                       HOTSPOT_JNI_NEWDOUBLEARRAY_RETURN(_ret_ref))
2802 
2803 // Return an address which will fault if the caller writes to it.
2804 
2805 static char* get_bad_address() {
2806   static char* bad_address = NULL;
2807   if (bad_address == NULL) {
2808     size_t size = os::vm_allocation_granularity();
2809     bad_address = os::reserve_memory(size);
2810     if (bad_address != NULL) {
2811       os::protect_memory(bad_address, size, os::MEM_PROT_READ,
2812                          /*is_committed*/false);
2813       MemTracker::record_virtual_memory_type((void*)bad_address, mtInternal);
2814     }
2815   }
2816   return bad_address;
2817 }
2818 
2819 
2820 
2821 #define DEFINE_GETSCALARARRAYELEMENTS(ElementTag,ElementType,Result, Tag \
2822                                       , EntryProbe, ReturnProbe) \
2823 \
2824 JNI_ENTRY_NO_PRESERVE(ElementType*, \
2825           jni_Get##Result##ArrayElements(JNIEnv *env, ElementType##Array array, jboolean *isCopy)) \
2826   JNIWrapper("Get" XSTR(Result) "ArrayElements"); \
2827   EntryProbe; \
2828   /* allocate an chunk of memory in c land */ \
2829   typeArrayOop a = typeArrayOop(JNIHandles::resolve_non_null(array)); \
2830   ElementType* result; \
2831   int len = a->length(); \
2832   if (len == 0) { \
2833     if (isCopy != NULL) { \
2834       *isCopy = JNI_FALSE; \
2835     } \
2836     /* Empty array: legal but useless, can't return NULL. \
2837      * Return a pointer to something useless. \
2838      * Avoid asserts in typeArrayOop. */ \
2839     result = (ElementType*)get_bad_address(); \
2840   } else { \
2841     /* JNI Specification states return NULL on OOM */                    \
2842     result = NEW_C_HEAP_ARRAY_RETURN_NULL(ElementType, len, mtInternal); \
2843     if (result != NULL) {                                                \
2844       /* copy the array to the c chunk */                                \
2845       ArrayAccess<>::arraycopy_to_native(a, typeArrayOopDesc::element_offset<ElementType>(0), \
2846                                          result, len);                   \
2847       if (isCopy) {                                                      \
2848         *isCopy = JNI_TRUE;                                              \
2849       }                                                                  \
2850     }                                                                    \
2851   } \
2852   ReturnProbe; \
2853   return result; \
2854 JNI_END
2855 
2856 DEFINE_GETSCALARARRAYELEMENTS(T_BOOLEAN, jboolean, Boolean, bool
2857                               , HOTSPOT_JNI_GETBOOLEANARRAYELEMENTS_ENTRY(env, array, (uintptr_t *) isCopy),
2858                               HOTSPOT_JNI_GETBOOLEANARRAYELEMENTS_RETURN((uintptr_t*)result))
2859 DEFINE_GETSCALARARRAYELEMENTS(T_BYTE,    jbyte,    Byte,    byte
2860                               , HOTSPOT_JNI_GETBYTEARRAYELEMENTS_ENTRY(env, array, (uintptr_t *) isCopy),
2861                               HOTSPOT_JNI_GETBYTEARRAYELEMENTS_RETURN((char*)result))
2862 DEFINE_GETSCALARARRAYELEMENTS(T_SHORT,   jshort,   Short,   short
2863                               , HOTSPOT_JNI_GETSHORTARRAYELEMENTS_ENTRY(env, (uint16_t*) array, (uintptr_t *) isCopy),
2864                               HOTSPOT_JNI_GETSHORTARRAYELEMENTS_RETURN((uint16_t*)result))
2865 DEFINE_GETSCALARARRAYELEMENTS(T_CHAR,    jchar,    Char,    char
2866                               , HOTSPOT_JNI_GETCHARARRAYELEMENTS_ENTRY(env, (uint16_t*) array, (uintptr_t *) isCopy),
2867                               HOTSPOT_JNI_GETCHARARRAYELEMENTS_RETURN(result))
2868 DEFINE_GETSCALARARRAYELEMENTS(T_INT,     jint,     Int,     int
2869                               , HOTSPOT_JNI_GETINTARRAYELEMENTS_ENTRY(env, array, (uintptr_t *) isCopy),
2870                               HOTSPOT_JNI_GETINTARRAYELEMENTS_RETURN((uint32_t*)result))
2871 DEFINE_GETSCALARARRAYELEMENTS(T_LONG,    jlong,    Long,    long
2872                               , HOTSPOT_JNI_GETLONGARRAYELEMENTS_ENTRY(env, array, (uintptr_t *) isCopy),
2873                               HOTSPOT_JNI_GETLONGARRAYELEMENTS_RETURN(((uintptr_t*)result)))
2874 // Float and double probes don't return value because dtrace doesn't currently support it
2875 DEFINE_GETSCALARARRAYELEMENTS(T_FLOAT,   jfloat,   Float,   float
2876                               , HOTSPOT_JNI_GETFLOATARRAYELEMENTS_ENTRY(env, array, (uintptr_t *) isCopy),
2877                               HOTSPOT_JNI_GETFLOATARRAYELEMENTS_RETURN(result))
2878 DEFINE_GETSCALARARRAYELEMENTS(T_DOUBLE,  jdouble,  Double,  double
2879                               , HOTSPOT_JNI_GETDOUBLEARRAYELEMENTS_ENTRY(env, array, (uintptr_t *) isCopy),
2880                               HOTSPOT_JNI_GETDOUBLEARRAYELEMENTS_RETURN(result))
2881 
2882 
2883 #define DEFINE_RELEASESCALARARRAYELEMENTS(ElementTag,ElementType,Result,Tag \
2884                                           , EntryProbe, ReturnProbe);\
2885 \
2886 JNI_ENTRY_NO_PRESERVE(void, \
2887           jni_Release##Result##ArrayElements(JNIEnv *env, ElementType##Array array, \
2888                                              ElementType *buf, jint mode)) \
2889   JNIWrapper("Release" XSTR(Result) "ArrayElements"); \
2890   EntryProbe; \
2891   typeArrayOop a = typeArrayOop(JNIHandles::resolve_non_null(array)); \
2892   int len = a->length(); \
2893   if (len != 0) {   /* Empty array:  nothing to free or copy. */  \
2894     if ((mode == 0) || (mode == JNI_COMMIT)) { \
2895       ArrayAccess<>::arraycopy_from_native(buf, a, typeArrayOopDesc::element_offset<ElementType>(0), len); \
2896     } \
2897     if ((mode == 0) || (mode == JNI_ABORT)) { \
2898       FreeHeap(buf); \
2899     } \
2900   } \
2901   ReturnProbe; \
2902 JNI_END
2903 
2904 DEFINE_RELEASESCALARARRAYELEMENTS(T_BOOLEAN, jboolean, Boolean, bool
2905                                   , HOTSPOT_JNI_RELEASEBOOLEANARRAYELEMENTS_ENTRY(env, array, (uintptr_t *) buf, mode),
2906                                   HOTSPOT_JNI_RELEASEBOOLEANARRAYELEMENTS_RETURN())
2907 DEFINE_RELEASESCALARARRAYELEMENTS(T_BYTE,    jbyte,    Byte,    byte
2908                                   , HOTSPOT_JNI_RELEASEBYTEARRAYELEMENTS_ENTRY(env, array, (char *) buf, mode),
2909                                   HOTSPOT_JNI_RELEASEBYTEARRAYELEMENTS_RETURN())
2910 DEFINE_RELEASESCALARARRAYELEMENTS(T_SHORT,   jshort,   Short,   short
2911                                   ,  HOTSPOT_JNI_RELEASESHORTARRAYELEMENTS_ENTRY(env, array, (uint16_t *) buf, mode),
2912                                   HOTSPOT_JNI_RELEASESHORTARRAYELEMENTS_RETURN())
2913 DEFINE_RELEASESCALARARRAYELEMENTS(T_CHAR,    jchar,    Char,    char
2914                                   ,  HOTSPOT_JNI_RELEASECHARARRAYELEMENTS_ENTRY(env, array, (uint16_t *) buf, mode),
2915                                   HOTSPOT_JNI_RELEASECHARARRAYELEMENTS_RETURN())
2916 DEFINE_RELEASESCALARARRAYELEMENTS(T_INT,     jint,     Int,     int
2917                                   , HOTSPOT_JNI_RELEASEINTARRAYELEMENTS_ENTRY(env, array, (uint32_t *) buf, mode),
2918                                   HOTSPOT_JNI_RELEASEINTARRAYELEMENTS_RETURN())
2919 DEFINE_RELEASESCALARARRAYELEMENTS(T_LONG,    jlong,    Long,    long
2920                                   , HOTSPOT_JNI_RELEASELONGARRAYELEMENTS_ENTRY(env, array, (uintptr_t *) buf, mode),
2921                                   HOTSPOT_JNI_RELEASELONGARRAYELEMENTS_RETURN())
2922 DEFINE_RELEASESCALARARRAYELEMENTS(T_FLOAT,   jfloat,   Float,   float
2923                                   , HOTSPOT_JNI_RELEASEFLOATARRAYELEMENTS_ENTRY(env, array, (float *) buf, mode),
2924                                   HOTSPOT_JNI_RELEASEFLOATARRAYELEMENTS_RETURN())
2925 DEFINE_RELEASESCALARARRAYELEMENTS(T_DOUBLE,  jdouble,  Double,  double
2926                                   , HOTSPOT_JNI_RELEASEDOUBLEARRAYELEMENTS_ENTRY(env, array, (double *) buf, mode),
2927                                   HOTSPOT_JNI_RELEASEDOUBLEARRAYELEMENTS_RETURN())
2928 
2929 static void check_bounds(jsize start, jsize copy_len, jsize array_len, TRAPS) {
2930   ResourceMark rm(THREAD);
2931   if (copy_len < 0) {
2932     stringStream ss;
2933     ss.print("Length %d is negative", copy_len);
2934     THROW_MSG(vmSymbols::java_lang_ArrayIndexOutOfBoundsException(), ss.as_string());
2935   } else if (start < 0 || (start > array_len - copy_len)) {
2936     stringStream ss;
2937     ss.print("Array region %d.." INT64_FORMAT " out of bounds for length %d",
2938              start, (int64_t)start+(int64_t)copy_len, array_len);
2939     THROW_MSG(vmSymbols::java_lang_ArrayIndexOutOfBoundsException(), ss.as_string());
2940   }
2941 }
2942 
2943 #define DEFINE_GETSCALARARRAYREGION(ElementTag,ElementType,Result, Tag \
2944                                     , EntryProbe, ReturnProbe); \
2945   DT_VOID_RETURN_MARK_DECL(Get##Result##ArrayRegion \
2946                            , ReturnProbe); \
2947 \
2948 JNI_ENTRY(void, \
2949 jni_Get##Result##ArrayRegion(JNIEnv *env, ElementType##Array array, jsize start, \
2950              jsize len, ElementType *buf)) \
2951   JNIWrapper("Get" XSTR(Result) "ArrayRegion"); \
2952   EntryProbe; \
2953   DT_VOID_RETURN_MARK(Get##Result##ArrayRegion); \
2954   typeArrayOop src = typeArrayOop(JNIHandles::resolve_non_null(array)); \
2955   check_bounds(start, len, src->length(), CHECK); \
2956   if (len > 0) {    \
2957     ArrayAccess<>::arraycopy_to_native(src, typeArrayOopDesc::element_offset<ElementType>(start), buf, len); \
2958   } \
2959 JNI_END
2960 
2961 DEFINE_GETSCALARARRAYREGION(T_BOOLEAN, jboolean,Boolean, bool
2962                             , HOTSPOT_JNI_GETBOOLEANARRAYREGION_ENTRY(env, array, start, len, (uintptr_t *) buf),
2963                             HOTSPOT_JNI_GETBOOLEANARRAYREGION_RETURN());
2964 DEFINE_GETSCALARARRAYREGION(T_BYTE,    jbyte,   Byte,    byte
2965                             ,  HOTSPOT_JNI_GETBYTEARRAYREGION_ENTRY(env, array, start, len, (char *) buf),
2966                             HOTSPOT_JNI_GETBYTEARRAYREGION_RETURN());
2967 DEFINE_GETSCALARARRAYREGION(T_SHORT,   jshort,  Short,   short
2968                             , HOTSPOT_JNI_GETSHORTARRAYREGION_ENTRY(env, array, start, len, (uint16_t *) buf),
2969                             HOTSPOT_JNI_GETSHORTARRAYREGION_RETURN());
2970 DEFINE_GETSCALARARRAYREGION(T_CHAR,    jchar,   Char,    char
2971                             ,  HOTSPOT_JNI_GETCHARARRAYREGION_ENTRY(env, array, start, len, (uint16_t*) buf),
2972                             HOTSPOT_JNI_GETCHARARRAYREGION_RETURN());
2973 DEFINE_GETSCALARARRAYREGION(T_INT,     jint,    Int,     int
2974                             , HOTSPOT_JNI_GETINTARRAYREGION_ENTRY(env, array, start, len, (uint32_t*) buf),
2975                             HOTSPOT_JNI_GETINTARRAYREGION_RETURN());
2976 DEFINE_GETSCALARARRAYREGION(T_LONG,    jlong,   Long,    long
2977                             ,  HOTSPOT_JNI_GETLONGARRAYREGION_ENTRY(env, array, start, len, (uintptr_t *) buf),
2978                             HOTSPOT_JNI_GETLONGARRAYREGION_RETURN());
2979 DEFINE_GETSCALARARRAYREGION(T_FLOAT,   jfloat,  Float,   float
2980                             , HOTSPOT_JNI_GETFLOATARRAYREGION_ENTRY(env, array, start, len, (float *) buf),
2981                             HOTSPOT_JNI_GETFLOATARRAYREGION_RETURN());
2982 DEFINE_GETSCALARARRAYREGION(T_DOUBLE,  jdouble, Double,  double
2983                             , HOTSPOT_JNI_GETDOUBLEARRAYREGION_ENTRY(env, array, start, len, (double *) buf),
2984                             HOTSPOT_JNI_GETDOUBLEARRAYREGION_RETURN());
2985 
2986 
2987 #define DEFINE_SETSCALARARRAYREGION(ElementTag,ElementType,Result, Tag \
2988                                     , EntryProbe, ReturnProbe); \
2989   DT_VOID_RETURN_MARK_DECL(Set##Result##ArrayRegion \
2990                            ,ReturnProbe);           \
2991 \
2992 JNI_ENTRY(void, \
2993 jni_Set##Result##ArrayRegion(JNIEnv *env, ElementType##Array array, jsize start, \
2994              jsize len, const ElementType *buf)) \
2995   JNIWrapper("Set" XSTR(Result) "ArrayRegion"); \
2996   EntryProbe; \
2997   DT_VOID_RETURN_MARK(Set##Result##ArrayRegion); \
2998   typeArrayOop dst = typeArrayOop(JNIHandles::resolve_non_null(array)); \
2999   check_bounds(start, len, dst->length(), CHECK); \
3000   if (len > 0) { \
3001     ArrayAccess<>::arraycopy_from_native(buf, dst, typeArrayOopDesc::element_offset<ElementType>(start), len); \
3002   } \
3003 JNI_END
3004 
3005 DEFINE_SETSCALARARRAYREGION(T_BOOLEAN, jboolean, Boolean, bool
3006                             , HOTSPOT_JNI_SETBOOLEANARRAYREGION_ENTRY(env, array, start, len, (uintptr_t *)buf),
3007                             HOTSPOT_JNI_SETBOOLEANARRAYREGION_RETURN())
3008 DEFINE_SETSCALARARRAYREGION(T_BYTE,    jbyte,    Byte,    byte
3009                             , HOTSPOT_JNI_SETBYTEARRAYREGION_ENTRY(env, array, start, len, (char *) buf),
3010                             HOTSPOT_JNI_SETBYTEARRAYREGION_RETURN())
3011 DEFINE_SETSCALARARRAYREGION(T_SHORT,   jshort,   Short,   short
3012                             , HOTSPOT_JNI_SETSHORTARRAYREGION_ENTRY(env, array, start, len, (uint16_t *) buf),
3013                             HOTSPOT_JNI_SETSHORTARRAYREGION_RETURN())
3014 DEFINE_SETSCALARARRAYREGION(T_CHAR,    jchar,    Char,    char
3015                             , HOTSPOT_JNI_SETCHARARRAYREGION_ENTRY(env, array, start, len, (uint16_t *) buf),
3016                             HOTSPOT_JNI_SETCHARARRAYREGION_RETURN())
3017 DEFINE_SETSCALARARRAYREGION(T_INT,     jint,     Int,     int
3018                             , HOTSPOT_JNI_SETINTARRAYREGION_ENTRY(env, array, start, len, (uint32_t *) buf),
3019                             HOTSPOT_JNI_SETINTARRAYREGION_RETURN())
3020 DEFINE_SETSCALARARRAYREGION(T_LONG,    jlong,    Long,    long
3021                             , HOTSPOT_JNI_SETLONGARRAYREGION_ENTRY(env, array, start, len, (uintptr_t *) buf),
3022                             HOTSPOT_JNI_SETLONGARRAYREGION_RETURN())
3023 DEFINE_SETSCALARARRAYREGION(T_FLOAT,   jfloat,   Float,   float
3024                             , HOTSPOT_JNI_SETFLOATARRAYREGION_ENTRY(env, array, start, len, (float *) buf),
3025                             HOTSPOT_JNI_SETFLOATARRAYREGION_RETURN())
3026 DEFINE_SETSCALARARRAYREGION(T_DOUBLE,  jdouble,  Double,  double
3027                             , HOTSPOT_JNI_SETDOUBLEARRAYREGION_ENTRY(env, array, start, len, (double *) buf),
3028                             HOTSPOT_JNI_SETDOUBLEARRAYREGION_RETURN())
3029 
3030 
3031 DT_RETURN_MARK_DECL(RegisterNatives, jint
3032                     , HOTSPOT_JNI_REGISTERNATIVES_RETURN(_ret_ref));
3033 
3034 JNI_ENTRY(jint, jni_RegisterNatives(JNIEnv *env, jclass clazz,
3035                                     const JNINativeMethod *methods,
3036                                     jint nMethods))
3037   JNIWrapper("RegisterNatives");
3038   HOTSPOT_JNI_REGISTERNATIVES_ENTRY(env, clazz, (void *) methods, nMethods);
3039   jint ret = 0;
3040   DT_RETURN_MARK(RegisterNatives, jint, (const jint&)ret);
3041 
3042   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(clazz));
3043 
3044   for (int index = 0; index < nMethods; index++) {
3045     const char* meth_name = methods[index].name;
3046     const char* meth_sig = methods[index].signature;
3047     int meth_name_len = (int)strlen(meth_name);
3048 
3049     // The class should have been loaded (we have an instance of the class
3050     // passed in) so the method and signature should already be in the symbol
3051     // table.  If they're not there, the method doesn't exist.
3052     TempNewSymbol  name = SymbolTable::probe(meth_name, meth_name_len);
3053     TempNewSymbol  signature = SymbolTable::probe(meth_sig, (int)strlen(meth_sig));
3054 
3055     if (name == NULL || signature == NULL) {
3056       ResourceMark rm;
3057       stringStream st;
3058       st.print("Method %s.%s%s not found", k->external_name(), meth_name, meth_sig);
3059       // Must return negative value on failure
3060       THROW_MSG_(vmSymbols::java_lang_NoSuchMethodError(), st.as_string(), -1);
3061     }
3062 
3063     bool res = Method::register_native(k, name, signature,
3064                                        (address) methods[index].fnPtr, THREAD);
3065     if (!res) {
3066       ret = -1;
3067       break;
3068     }
3069   }
3070   return ret;
3071 JNI_END
3072 
3073 
3074 JNI_ENTRY(jint, jni_UnregisterNatives(JNIEnv *env, jclass clazz))
3075   JNIWrapper("UnregisterNatives");
3076  HOTSPOT_JNI_UNREGISTERNATIVES_ENTRY(env, clazz);
3077   Klass* k   = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(clazz));
3078   //%note jni_2
3079   if (k->is_instance_klass()) {
3080     for (int index = 0; index < InstanceKlass::cast(k)->methods()->length(); index++) {
3081       Method* m = InstanceKlass::cast(k)->methods()->at(index);
3082       if (m->is_native()) {
3083         m->clear_native_function();
3084         m->set_signature_handler(NULL);
3085       }
3086     }
3087   }
3088  HOTSPOT_JNI_UNREGISTERNATIVES_RETURN(0);
3089   return 0;
3090 JNI_END
3091 
3092 //
3093 // Monitor functions
3094 //
3095 
3096 DT_RETURN_MARK_DECL(MonitorEnter, jint
3097                     , HOTSPOT_JNI_MONITORENTER_RETURN(_ret_ref));
3098 
3099 JNI_ENTRY(jint, jni_MonitorEnter(JNIEnv *env, jobject jobj))
3100  HOTSPOT_JNI_MONITORENTER_ENTRY(env, jobj);
3101   jint ret = JNI_ERR;
3102   DT_RETURN_MARK(MonitorEnter, jint, (const jint&)ret);
3103 
3104   // If the object is null, we can't do anything with it
3105   if (jobj == NULL) {
3106     THROW_(vmSymbols::java_lang_NullPointerException(), JNI_ERR);
3107   }
3108 
3109   Handle obj(thread, JNIHandles::resolve_non_null(jobj));
3110   ObjectSynchronizer::jni_enter(obj, CHECK_(JNI_ERR));
3111   ret = JNI_OK;
3112   return ret;
3113 JNI_END
3114 
3115 DT_RETURN_MARK_DECL(MonitorExit, jint
3116                     , HOTSPOT_JNI_MONITOREXIT_RETURN(_ret_ref));
3117 
3118 JNI_ENTRY(jint, jni_MonitorExit(JNIEnv *env, jobject jobj))
3119  HOTSPOT_JNI_MONITOREXIT_ENTRY(env, jobj);
3120   jint ret = JNI_ERR;
3121   DT_RETURN_MARK(MonitorExit, jint, (const jint&)ret);
3122 
3123   // Don't do anything with a null object
3124   if (jobj == NULL) {
3125     THROW_(vmSymbols::java_lang_NullPointerException(), JNI_ERR);
3126   }
3127 
3128   Handle obj(THREAD, JNIHandles::resolve_non_null(jobj));
3129   ObjectSynchronizer::jni_exit(obj(), CHECK_(JNI_ERR));
3130 
3131   ret = JNI_OK;
3132   return ret;
3133 JNI_END
3134 
3135 //
3136 // Extensions
3137 //
3138 
3139 DT_VOID_RETURN_MARK_DECL(GetStringRegion
3140                          , HOTSPOT_JNI_GETSTRINGREGION_RETURN());
3141 
3142 JNI_ENTRY(void, jni_GetStringRegion(JNIEnv *env, jstring string, jsize start, jsize len, jchar *buf))
3143   JNIWrapper("GetStringRegion");
3144  HOTSPOT_JNI_GETSTRINGREGION_ENTRY(env, string, start, len, buf);
3145   DT_VOID_RETURN_MARK(GetStringRegion);
3146   oop s = JNIHandles::resolve_non_null(string);
3147   typeArrayOop s_value = java_lang_String::value(s);
3148   int s_len = java_lang_String::length(s, s_value);
3149   if (start < 0 || len < 0 || start > s_len - len) {
3150     THROW(vmSymbols::java_lang_StringIndexOutOfBoundsException());
3151   } else {
3152     if (len > 0) {
3153       bool is_latin1 = java_lang_String::is_latin1(s);
3154       if (!is_latin1) {
3155         ArrayAccess<>::arraycopy_to_native(s_value, typeArrayOopDesc::element_offset<jchar>(start),
3156                                            buf, len);
3157       } else {
3158         for (int i = 0; i < len; i++) {
3159           buf[i] = ((jchar) s_value->byte_at(i + start)) & 0xff;
3160         }
3161       }
3162     }
3163   }
3164 JNI_END
3165 
3166 DT_VOID_RETURN_MARK_DECL(GetStringUTFRegion
3167                          , HOTSPOT_JNI_GETSTRINGUTFREGION_RETURN());
3168 
3169 JNI_ENTRY(void, jni_GetStringUTFRegion(JNIEnv *env, jstring string, jsize start, jsize len, char *buf))
3170   JNIWrapper("GetStringUTFRegion");
3171  HOTSPOT_JNI_GETSTRINGUTFREGION_ENTRY(env, string, start, len, buf);
3172   DT_VOID_RETURN_MARK(GetStringUTFRegion);
3173   oop s = JNIHandles::resolve_non_null(string);
3174   typeArrayOop s_value = java_lang_String::value(s);
3175   int s_len = java_lang_String::length(s, s_value);
3176   if (start < 0 || len < 0 || start > s_len - len) {
3177     THROW(vmSymbols::java_lang_StringIndexOutOfBoundsException());
3178   } else {
3179     //%note jni_7
3180     if (len > 0) {
3181       // Assume the buffer is large enough as the JNI spec. does not require user error checking
3182       java_lang_String::as_utf8_string(s, s_value, start, len, buf, INT_MAX);
3183       // as_utf8_string null-terminates the result string
3184     } else {
3185       // JDK null-terminates the buffer even in len is zero
3186       if (buf != NULL) {
3187         buf[0] = 0;
3188       }
3189     }
3190   }
3191 JNI_END
3192 
3193 static oop lock_gc_or_pin_object(JavaThread* thread, jobject obj) {
3194   if (Universe::heap()->supports_object_pinning()) {
3195     const oop o = JNIHandles::resolve_non_null(obj);
3196     return Universe::heap()->pin_object(thread, o);
3197   } else {
3198     GCLocker::lock_critical(thread);
3199     return JNIHandles::resolve_non_null(obj);
3200   }
3201 }
3202 
3203 static void unlock_gc_or_unpin_object(JavaThread* thread, jobject obj) {
3204   if (Universe::heap()->supports_object_pinning()) {
3205     const oop o = JNIHandles::resolve_non_null(obj);
3206     return Universe::heap()->unpin_object(thread, o);
3207   } else {
3208     GCLocker::unlock_critical(thread);
3209   }
3210 }
3211 
3212 JNI_ENTRY(void*, jni_GetPrimitiveArrayCritical(JNIEnv *env, jarray array, jboolean *isCopy))
3213   JNIWrapper("GetPrimitiveArrayCritical");
3214  HOTSPOT_JNI_GETPRIMITIVEARRAYCRITICAL_ENTRY(env, array, (uintptr_t *) isCopy);
3215   if (isCopy != NULL) {
3216     *isCopy = JNI_FALSE;
3217   }
3218   oop a = lock_gc_or_pin_object(thread, array);
3219   assert(a->is_array(), "just checking");
3220   BasicType type;
3221   if (a->is_objArray()) {
3222     type = T_OBJECT;
3223   } else {
3224     type = TypeArrayKlass::cast(a->klass())->element_type();
3225   }
3226   void* ret = arrayOop(a)->base(type);
3227  HOTSPOT_JNI_GETPRIMITIVEARRAYCRITICAL_RETURN(ret);
3228   return ret;
3229 JNI_END
3230 
3231 
3232 JNI_ENTRY(void, jni_ReleasePrimitiveArrayCritical(JNIEnv *env, jarray array, void *carray, jint mode))
3233   JNIWrapper("ReleasePrimitiveArrayCritical");
3234   HOTSPOT_JNI_RELEASEPRIMITIVEARRAYCRITICAL_ENTRY(env, array, carray, mode);
3235   unlock_gc_or_unpin_object(thread, array);
3236 HOTSPOT_JNI_RELEASEPRIMITIVEARRAYCRITICAL_RETURN();
3237 JNI_END
3238 
3239 
3240 JNI_ENTRY(const jchar*, jni_GetStringCritical(JNIEnv *env, jstring string, jboolean *isCopy))
3241   JNIWrapper("GetStringCritical");
3242   HOTSPOT_JNI_GETSTRINGCRITICAL_ENTRY(env, string, (uintptr_t *) isCopy);
3243   oop s = lock_gc_or_pin_object(thread, string);
3244   typeArrayOop s_value = java_lang_String::value(s);
3245   bool is_latin1 = java_lang_String::is_latin1(s);
3246   if (isCopy != NULL) {
3247     *isCopy = is_latin1 ? JNI_TRUE : JNI_FALSE;
3248   }
3249   jchar* ret;
3250   if (!is_latin1) {
3251     ret = (jchar*) s_value->base(T_CHAR);
3252   } else {
3253     // Inflate latin1 encoded string to UTF16
3254     int s_len = java_lang_String::length(s, s_value);
3255     ret = NEW_C_HEAP_ARRAY_RETURN_NULL(jchar, s_len + 1, mtInternal);  // add one for zero termination
3256     /* JNI Specification states return NULL on OOM */
3257     if (ret != NULL) {
3258       for (int i = 0; i < s_len; i++) {
3259         ret[i] = ((jchar) s_value->byte_at(i)) & 0xff;
3260       }
3261       ret[s_len] = 0;
3262     }
3263   }
3264  HOTSPOT_JNI_GETSTRINGCRITICAL_RETURN((uint16_t *) ret);
3265   return ret;
3266 JNI_END
3267 
3268 
3269 JNI_ENTRY(void, jni_ReleaseStringCritical(JNIEnv *env, jstring str, const jchar *chars))
3270   JNIWrapper("ReleaseStringCritical");
3271   HOTSPOT_JNI_RELEASESTRINGCRITICAL_ENTRY(env, str, (uint16_t *) chars);
3272   // The str and chars arguments are ignored for UTF16 strings
3273   oop s = JNIHandles::resolve_non_null(str);
3274   bool is_latin1 = java_lang_String::is_latin1(s);
3275   if (is_latin1) {
3276     // For latin1 string, free jchar array allocated by earlier call to GetStringCritical.
3277     // This assumes that ReleaseStringCritical bookends GetStringCritical.
3278     FREE_C_HEAP_ARRAY(jchar, chars);
3279   }
3280   unlock_gc_or_unpin_object(thread, str);
3281 HOTSPOT_JNI_RELEASESTRINGCRITICAL_RETURN();
3282 JNI_END
3283 
3284 
3285 JNI_ENTRY(jweak, jni_NewWeakGlobalRef(JNIEnv *env, jobject ref))
3286   JNIWrapper("jni_NewWeakGlobalRef");
3287  HOTSPOT_JNI_NEWWEAKGLOBALREF_ENTRY(env, ref);
3288   Handle ref_handle(thread, JNIHandles::resolve(ref));
3289   jweak ret = JNIHandles::make_weak_global(ref_handle);
3290  HOTSPOT_JNI_NEWWEAKGLOBALREF_RETURN(ret);
3291   return ret;
3292 JNI_END
3293 
3294 // Must be JNI_ENTRY (with HandleMark)
3295 JNI_ENTRY(void, jni_DeleteWeakGlobalRef(JNIEnv *env, jweak ref))
3296   JNIWrapper("jni_DeleteWeakGlobalRef");
3297   HOTSPOT_JNI_DELETEWEAKGLOBALREF_ENTRY(env, ref);
3298   JNIHandles::destroy_weak_global(ref);
3299   HOTSPOT_JNI_DELETEWEAKGLOBALREF_RETURN();
3300 JNI_END
3301 
3302 
3303 JNI_ENTRY_NO_PRESERVE(jboolean, jni_ExceptionCheck(JNIEnv *env))
3304   JNIWrapper("jni_ExceptionCheck");
3305  HOTSPOT_JNI_EXCEPTIONCHECK_ENTRY(env);
3306   jni_check_async_exceptions(thread);
3307   jboolean ret = (thread->has_pending_exception()) ? JNI_TRUE : JNI_FALSE;
3308  HOTSPOT_JNI_EXCEPTIONCHECK_RETURN(ret);
3309   return ret;
3310 JNI_END
3311 
3312 
3313 // Initialization state for three routines below relating to
3314 // java.nio.DirectBuffers
3315 static          int directBufferSupportInitializeStarted = 0;
3316 static volatile int directBufferSupportInitializeEnded   = 0;
3317 static volatile int directBufferSupportInitializeFailed  = 0;
3318 static jclass    bufferClass                 = NULL;
3319 static jclass    directBufferClass           = NULL;
3320 static jclass    directByteBufferClass       = NULL;
3321 static jmethodID directByteBufferConstructor = NULL;
3322 static jfieldID  directBufferAddressField    = NULL;
3323 static jfieldID  bufferCapacityField         = NULL;
3324 
3325 static jclass lookupOne(JNIEnv* env, const char* name, TRAPS) {
3326   Handle loader;            // null (bootstrap) loader
3327   Handle protection_domain; // null protection domain
3328 
3329   TempNewSymbol sym = SymbolTable::new_symbol(name);
3330   jclass result =  find_class_from_class_loader(env, sym, true, loader, protection_domain, true, CHECK_NULL);
3331 
3332   if (log_is_enabled(Debug, class, resolve) && result != NULL) {
3333     trace_class_resolution(java_lang_Class::as_Klass(JNIHandles::resolve_non_null(result)));
3334   }
3335   return result;
3336 }
3337 
3338 // These lookups are done with the NULL (bootstrap) ClassLoader to
3339 // circumvent any security checks that would be done by jni_FindClass.
3340 JNI_ENTRY(bool, lookupDirectBufferClasses(JNIEnv* env))
3341 {
3342   if ((bufferClass           = lookupOne(env, "java/nio/Buffer", thread))           == NULL) { return false; }
3343   if ((directBufferClass     = lookupOne(env, "sun/nio/ch/DirectBuffer", thread))   == NULL) { return false; }
3344   if ((directByteBufferClass = lookupOne(env, "java/nio/DirectByteBuffer", thread)) == NULL) { return false; }
3345   return true;
3346 }
3347 JNI_END
3348 
3349 
3350 static bool initializeDirectBufferSupport(JNIEnv* env, JavaThread* thread) {
3351   if (directBufferSupportInitializeFailed) {
3352     return false;
3353   }
3354 
3355   if (Atomic::cmpxchg(1, &directBufferSupportInitializeStarted, 0) == 0) {
3356     if (!lookupDirectBufferClasses(env)) {
3357       directBufferSupportInitializeFailed = 1;
3358       return false;
3359     }
3360 
3361     // Make global references for these
3362     bufferClass           = (jclass) env->NewGlobalRef(bufferClass);
3363     directBufferClass     = (jclass) env->NewGlobalRef(directBufferClass);
3364     directByteBufferClass = (jclass) env->NewGlobalRef(directByteBufferClass);
3365 
3366     // Get needed field and method IDs
3367     directByteBufferConstructor = env->GetMethodID(directByteBufferClass, "<init>", "(JI)V");
3368     if (env->ExceptionCheck()) {
3369       env->ExceptionClear();
3370       directBufferSupportInitializeFailed = 1;
3371       return false;
3372     }
3373     directBufferAddressField    = env->GetFieldID(bufferClass, "address", "J");
3374     if (env->ExceptionCheck()) {
3375       env->ExceptionClear();
3376       directBufferSupportInitializeFailed = 1;
3377       return false;
3378     }
3379     bufferCapacityField         = env->GetFieldID(bufferClass, "capacity", "I");
3380     if (env->ExceptionCheck()) {
3381       env->ExceptionClear();
3382       directBufferSupportInitializeFailed = 1;
3383       return false;
3384     }
3385 
3386     if ((directByteBufferConstructor == NULL) ||
3387         (directBufferAddressField    == NULL) ||
3388         (bufferCapacityField         == NULL)) {
3389       directBufferSupportInitializeFailed = 1;
3390       return false;
3391     }
3392 
3393     directBufferSupportInitializeEnded = 1;
3394   } else {
3395     while (!directBufferSupportInitializeEnded && !directBufferSupportInitializeFailed) {
3396       os::naked_yield();
3397     }
3398   }
3399 
3400   return !directBufferSupportInitializeFailed;
3401 }
3402 
3403 extern "C" jobject JNICALL jni_NewDirectByteBuffer(JNIEnv *env, void* address, jlong capacity)
3404 {
3405   // thread_from_jni_environment() will block if VM is gone.
3406   JavaThread* thread = JavaThread::thread_from_jni_environment(env);
3407 
3408   JNIWrapper("jni_NewDirectByteBuffer");
3409  HOTSPOT_JNI_NEWDIRECTBYTEBUFFER_ENTRY(env, address, capacity);
3410 
3411   if (!directBufferSupportInitializeEnded) {
3412     if (!initializeDirectBufferSupport(env, thread)) {
3413       HOTSPOT_JNI_NEWDIRECTBYTEBUFFER_RETURN(NULL);
3414       return NULL;
3415     }
3416   }
3417 
3418   // Being paranoid about accidental sign extension on address
3419   jlong addr = (jlong) ((uintptr_t) address);
3420   // NOTE that package-private DirectByteBuffer constructor currently
3421   // takes int capacity
3422   jint  cap  = (jint)  capacity;
3423   jobject ret = env->NewObject(directByteBufferClass, directByteBufferConstructor, addr, cap);
3424   HOTSPOT_JNI_NEWDIRECTBYTEBUFFER_RETURN(ret);
3425   return ret;
3426 }
3427 
3428 DT_RETURN_MARK_DECL(GetDirectBufferAddress, void*
3429                     , HOTSPOT_JNI_GETDIRECTBUFFERADDRESS_RETURN((void*) _ret_ref));
3430 
3431 extern "C" void* JNICALL jni_GetDirectBufferAddress(JNIEnv *env, jobject buf)
3432 {
3433   // thread_from_jni_environment() will block if VM is gone.
3434   JavaThread* thread = JavaThread::thread_from_jni_environment(env);
3435 
3436   JNIWrapper("jni_GetDirectBufferAddress");
3437   HOTSPOT_JNI_GETDIRECTBUFFERADDRESS_ENTRY(env, buf);
3438   void* ret = NULL;
3439   DT_RETURN_MARK(GetDirectBufferAddress, void*, (const void*&)ret);
3440 
3441   if (!directBufferSupportInitializeEnded) {
3442     if (!initializeDirectBufferSupport(env, thread)) {
3443       return 0;
3444     }
3445   }
3446 
3447   if ((buf != NULL) && (!env->IsInstanceOf(buf, directBufferClass))) {
3448     return 0;
3449   }
3450 
3451   ret = (void*)(intptr_t)env->GetLongField(buf, directBufferAddressField);
3452   return ret;
3453 }
3454 
3455 DT_RETURN_MARK_DECL(GetDirectBufferCapacity, jlong
3456                     , HOTSPOT_JNI_GETDIRECTBUFFERCAPACITY_RETURN(_ret_ref));
3457 
3458 extern "C" jlong JNICALL jni_GetDirectBufferCapacity(JNIEnv *env, jobject buf)
3459 {
3460   // thread_from_jni_environment() will block if VM is gone.
3461   JavaThread* thread = JavaThread::thread_from_jni_environment(env);
3462 
3463   JNIWrapper("jni_GetDirectBufferCapacity");
3464   HOTSPOT_JNI_GETDIRECTBUFFERCAPACITY_ENTRY(env, buf);
3465   jlong ret = -1;
3466   DT_RETURN_MARK(GetDirectBufferCapacity, jlong, (const jlong&)ret);
3467 
3468   if (!directBufferSupportInitializeEnded) {
3469     if (!initializeDirectBufferSupport(env, thread)) {
3470       ret = 0;
3471       return ret;
3472     }
3473   }
3474 
3475   if (buf == NULL) {
3476     return -1;
3477   }
3478 
3479   if (!env->IsInstanceOf(buf, directBufferClass)) {
3480     return -1;
3481   }
3482 
3483   // NOTE that capacity is currently an int in the implementation
3484   ret = env->GetIntField(buf, bufferCapacityField);
3485   return ret;
3486 }
3487 
3488 
3489 JNI_LEAF(jint, jni_GetVersion(JNIEnv *env))
3490   JNIWrapper("GetVersion");
3491   HOTSPOT_JNI_GETVERSION_ENTRY(env);
3492   HOTSPOT_JNI_GETVERSION_RETURN(CurrentVersion);
3493   return CurrentVersion;
3494 JNI_END
3495 
3496 extern struct JavaVM_ main_vm;
3497 
3498 JNI_LEAF(jint, jni_GetJavaVM(JNIEnv *env, JavaVM **vm))
3499   JNIWrapper("jni_GetJavaVM");
3500   HOTSPOT_JNI_GETJAVAVM_ENTRY(env, (void **) vm);
3501   *vm  = (JavaVM *)(&main_vm);
3502   HOTSPOT_JNI_GETJAVAVM_RETURN(JNI_OK);
3503   return JNI_OK;
3504 JNI_END
3505 
3506 
3507 JNI_ENTRY(jobject, jni_GetModule(JNIEnv* env, jclass clazz))
3508   JNIWrapper("GetModule");
3509   return Modules::get_module(clazz, THREAD);
3510 JNI_END
3511 
3512 


























































































3513 // Structure containing all jni functions
3514 struct JNINativeInterface_ jni_NativeInterface = {
3515     NULL,
3516     NULL,
3517     NULL,
3518 
3519     NULL,
3520 
3521     jni_GetVersion,
3522 
3523     jni_DefineClass,
3524     jni_FindClass,
3525 
3526     jni_FromReflectedMethod,
3527     jni_FromReflectedField,
3528 
3529     jni_ToReflectedMethod,
3530 
3531     jni_GetSuperclass,
3532     jni_IsAssignableFrom,
3533 
3534     jni_ToReflectedField,
3535 
3536     jni_Throw,
3537     jni_ThrowNew,
3538     jni_ExceptionOccurred,
3539     jni_ExceptionDescribe,
3540     jni_ExceptionClear,
3541     jni_FatalError,
3542 
3543     jni_PushLocalFrame,
3544     jni_PopLocalFrame,
3545 
3546     jni_NewGlobalRef,
3547     jni_DeleteGlobalRef,
3548     jni_DeleteLocalRef,
3549     jni_IsSameObject,
3550 
3551     jni_NewLocalRef,
3552     jni_EnsureLocalCapacity,
3553 
3554     jni_AllocObject,
3555     jni_NewObject,
3556     jni_NewObjectV,
3557     jni_NewObjectA,
3558 
3559     jni_GetObjectClass,
3560     jni_IsInstanceOf,
3561 
3562     jni_GetMethodID,
3563 
3564     jni_CallObjectMethod,
3565     jni_CallObjectMethodV,
3566     jni_CallObjectMethodA,
3567     jni_CallBooleanMethod,
3568     jni_CallBooleanMethodV,
3569     jni_CallBooleanMethodA,
3570     jni_CallByteMethod,
3571     jni_CallByteMethodV,
3572     jni_CallByteMethodA,
3573     jni_CallCharMethod,
3574     jni_CallCharMethodV,
3575     jni_CallCharMethodA,
3576     jni_CallShortMethod,
3577     jni_CallShortMethodV,
3578     jni_CallShortMethodA,
3579     jni_CallIntMethod,
3580     jni_CallIntMethodV,
3581     jni_CallIntMethodA,
3582     jni_CallLongMethod,
3583     jni_CallLongMethodV,
3584     jni_CallLongMethodA,
3585     jni_CallFloatMethod,
3586     jni_CallFloatMethodV,
3587     jni_CallFloatMethodA,
3588     jni_CallDoubleMethod,
3589     jni_CallDoubleMethodV,
3590     jni_CallDoubleMethodA,
3591     jni_CallVoidMethod,
3592     jni_CallVoidMethodV,
3593     jni_CallVoidMethodA,
3594 
3595     jni_CallNonvirtualObjectMethod,
3596     jni_CallNonvirtualObjectMethodV,
3597     jni_CallNonvirtualObjectMethodA,
3598     jni_CallNonvirtualBooleanMethod,
3599     jni_CallNonvirtualBooleanMethodV,
3600     jni_CallNonvirtualBooleanMethodA,
3601     jni_CallNonvirtualByteMethod,
3602     jni_CallNonvirtualByteMethodV,
3603     jni_CallNonvirtualByteMethodA,
3604     jni_CallNonvirtualCharMethod,
3605     jni_CallNonvirtualCharMethodV,
3606     jni_CallNonvirtualCharMethodA,
3607     jni_CallNonvirtualShortMethod,
3608     jni_CallNonvirtualShortMethodV,
3609     jni_CallNonvirtualShortMethodA,
3610     jni_CallNonvirtualIntMethod,
3611     jni_CallNonvirtualIntMethodV,
3612     jni_CallNonvirtualIntMethodA,
3613     jni_CallNonvirtualLongMethod,
3614     jni_CallNonvirtualLongMethodV,
3615     jni_CallNonvirtualLongMethodA,
3616     jni_CallNonvirtualFloatMethod,
3617     jni_CallNonvirtualFloatMethodV,
3618     jni_CallNonvirtualFloatMethodA,
3619     jni_CallNonvirtualDoubleMethod,
3620     jni_CallNonvirtualDoubleMethodV,
3621     jni_CallNonvirtualDoubleMethodA,
3622     jni_CallNonvirtualVoidMethod,
3623     jni_CallNonvirtualVoidMethodV,
3624     jni_CallNonvirtualVoidMethodA,
3625 
3626     jni_GetFieldID,
3627 
3628     jni_GetObjectField,
3629     jni_GetBooleanField,
3630     jni_GetByteField,
3631     jni_GetCharField,
3632     jni_GetShortField,
3633     jni_GetIntField,
3634     jni_GetLongField,
3635     jni_GetFloatField,
3636     jni_GetDoubleField,
3637 
3638     jni_SetObjectField,
3639     jni_SetBooleanField,
3640     jni_SetByteField,
3641     jni_SetCharField,
3642     jni_SetShortField,
3643     jni_SetIntField,
3644     jni_SetLongField,
3645     jni_SetFloatField,
3646     jni_SetDoubleField,
3647 
3648     jni_GetStaticMethodID,
3649 
3650     jni_CallStaticObjectMethod,
3651     jni_CallStaticObjectMethodV,
3652     jni_CallStaticObjectMethodA,
3653     jni_CallStaticBooleanMethod,
3654     jni_CallStaticBooleanMethodV,
3655     jni_CallStaticBooleanMethodA,
3656     jni_CallStaticByteMethod,
3657     jni_CallStaticByteMethodV,
3658     jni_CallStaticByteMethodA,
3659     jni_CallStaticCharMethod,
3660     jni_CallStaticCharMethodV,
3661     jni_CallStaticCharMethodA,
3662     jni_CallStaticShortMethod,
3663     jni_CallStaticShortMethodV,
3664     jni_CallStaticShortMethodA,
3665     jni_CallStaticIntMethod,
3666     jni_CallStaticIntMethodV,
3667     jni_CallStaticIntMethodA,
3668     jni_CallStaticLongMethod,
3669     jni_CallStaticLongMethodV,
3670     jni_CallStaticLongMethodA,
3671     jni_CallStaticFloatMethod,
3672     jni_CallStaticFloatMethodV,
3673     jni_CallStaticFloatMethodA,
3674     jni_CallStaticDoubleMethod,
3675     jni_CallStaticDoubleMethodV,
3676     jni_CallStaticDoubleMethodA,
3677     jni_CallStaticVoidMethod,
3678     jni_CallStaticVoidMethodV,
3679     jni_CallStaticVoidMethodA,
3680 
3681     jni_GetStaticFieldID,
3682 
3683     jni_GetStaticObjectField,
3684     jni_GetStaticBooleanField,
3685     jni_GetStaticByteField,
3686     jni_GetStaticCharField,
3687     jni_GetStaticShortField,
3688     jni_GetStaticIntField,
3689     jni_GetStaticLongField,
3690     jni_GetStaticFloatField,
3691     jni_GetStaticDoubleField,
3692 
3693     jni_SetStaticObjectField,
3694     jni_SetStaticBooleanField,
3695     jni_SetStaticByteField,
3696     jni_SetStaticCharField,
3697     jni_SetStaticShortField,
3698     jni_SetStaticIntField,
3699     jni_SetStaticLongField,
3700     jni_SetStaticFloatField,
3701     jni_SetStaticDoubleField,
3702 
3703     jni_NewString,
3704     jni_GetStringLength,
3705     jni_GetStringChars,
3706     jni_ReleaseStringChars,
3707 
3708     jni_NewStringUTF,
3709     jni_GetStringUTFLength,
3710     jni_GetStringUTFChars,
3711     jni_ReleaseStringUTFChars,
3712 
3713     jni_GetArrayLength,
3714 
3715     jni_NewObjectArray,
3716     jni_GetObjectArrayElement,
3717     jni_SetObjectArrayElement,
3718 
3719     jni_NewBooleanArray,
3720     jni_NewByteArray,
3721     jni_NewCharArray,
3722     jni_NewShortArray,
3723     jni_NewIntArray,
3724     jni_NewLongArray,
3725     jni_NewFloatArray,
3726     jni_NewDoubleArray,
3727 
3728     jni_GetBooleanArrayElements,
3729     jni_GetByteArrayElements,
3730     jni_GetCharArrayElements,
3731     jni_GetShortArrayElements,
3732     jni_GetIntArrayElements,
3733     jni_GetLongArrayElements,
3734     jni_GetFloatArrayElements,
3735     jni_GetDoubleArrayElements,
3736 
3737     jni_ReleaseBooleanArrayElements,
3738     jni_ReleaseByteArrayElements,
3739     jni_ReleaseCharArrayElements,
3740     jni_ReleaseShortArrayElements,
3741     jni_ReleaseIntArrayElements,
3742     jni_ReleaseLongArrayElements,
3743     jni_ReleaseFloatArrayElements,
3744     jni_ReleaseDoubleArrayElements,
3745 
3746     jni_GetBooleanArrayRegion,
3747     jni_GetByteArrayRegion,
3748     jni_GetCharArrayRegion,
3749     jni_GetShortArrayRegion,
3750     jni_GetIntArrayRegion,
3751     jni_GetLongArrayRegion,
3752     jni_GetFloatArrayRegion,
3753     jni_GetDoubleArrayRegion,
3754 
3755     jni_SetBooleanArrayRegion,
3756     jni_SetByteArrayRegion,
3757     jni_SetCharArrayRegion,
3758     jni_SetShortArrayRegion,
3759     jni_SetIntArrayRegion,
3760     jni_SetLongArrayRegion,
3761     jni_SetFloatArrayRegion,
3762     jni_SetDoubleArrayRegion,
3763 
3764     jni_RegisterNatives,
3765     jni_UnregisterNatives,
3766 
3767     jni_MonitorEnter,
3768     jni_MonitorExit,
3769 
3770     jni_GetJavaVM,
3771 
3772     jni_GetStringRegion,
3773     jni_GetStringUTFRegion,
3774 
3775     jni_GetPrimitiveArrayCritical,
3776     jni_ReleasePrimitiveArrayCritical,
3777 
3778     jni_GetStringCritical,
3779     jni_ReleaseStringCritical,
3780 
3781     jni_NewWeakGlobalRef,
3782     jni_DeleteWeakGlobalRef,
3783 
3784     jni_ExceptionCheck,
3785 
3786     jni_NewDirectByteBuffer,
3787     jni_GetDirectBufferAddress,
3788     jni_GetDirectBufferCapacity,
3789 
3790     // New 1_6 features
3791 
3792     jni_GetObjectRefType,
3793 
3794     // Module features
3795 
3796     jni_GetModule








3797 };
3798 
3799 
3800 // For jvmti use to modify jni function table.
3801 // Java threads in native contiues to run until it is transitioned
3802 // to VM at safepoint. Before the transition or before it is blocked
3803 // for safepoint it may access jni function table. VM could crash if
3804 // any java thread access the jni function table in the middle of memcpy.
3805 // To avoid this each function pointers are copied automically.
3806 void copy_jni_function_table(const struct JNINativeInterface_ *new_jni_NativeInterface) {
3807   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
3808   intptr_t *a = (intptr_t *) jni_functions();
3809   intptr_t *b = (intptr_t *) new_jni_NativeInterface;
3810   for (uint i=0; i <  sizeof(struct JNINativeInterface_)/sizeof(void *); i++) {
3811     Atomic::store(*b++, a++);
3812   }
3813 }
3814 
3815 void quicken_jni_functions() {
3816   // Replace Get<Primitive>Field with fast versions
3817   if (UseFastJNIAccessors && !VerifyJNIFields && !CountJNICalls && !CheckJNICalls) {
3818     address func;
3819     func = JNI_FastGetField::generate_fast_get_boolean_field();
3820     if (func != (address)-1) {
3821       jni_NativeInterface.GetBooleanField = (GetBooleanField_t)func;
3822     }
3823     func = JNI_FastGetField::generate_fast_get_byte_field();
3824     if (func != (address)-1) {
3825       jni_NativeInterface.GetByteField = (GetByteField_t)func;
3826     }
3827     func = JNI_FastGetField::generate_fast_get_char_field();
3828     if (func != (address)-1) {
3829       jni_NativeInterface.GetCharField = (GetCharField_t)func;
3830     }
3831     func = JNI_FastGetField::generate_fast_get_short_field();
3832     if (func != (address)-1) {
3833       jni_NativeInterface.GetShortField = (GetShortField_t)func;
3834     }
3835     func = JNI_FastGetField::generate_fast_get_int_field();
3836     if (func != (address)-1) {
3837       jni_NativeInterface.GetIntField = (GetIntField_t)func;
3838     }
3839     func = JNI_FastGetField::generate_fast_get_long_field();
3840     if (func != (address)-1) {
3841       jni_NativeInterface.GetLongField = (GetLongField_t)func;
3842     }
3843     func = JNI_FastGetField::generate_fast_get_float_field();
3844     if (func != (address)-1) {
3845       jni_NativeInterface.GetFloatField = (GetFloatField_t)func;
3846     }
3847     func = JNI_FastGetField::generate_fast_get_double_field();
3848     if (func != (address)-1) {
3849       jni_NativeInterface.GetDoubleField = (GetDoubleField_t)func;
3850     }
3851   }
3852 }
3853 
3854 // Returns the function structure
3855 struct JNINativeInterface_* jni_functions() {
3856 #if INCLUDE_JNI_CHECK
3857   if (CheckJNICalls) return jni_functions_check();
3858 #endif // INCLUDE_JNI_CHECK
3859   return &jni_NativeInterface;
3860 }
3861 
3862 // Returns the function structure
3863 struct JNINativeInterface_* jni_functions_nocheck() {
3864   return &jni_NativeInterface;
3865 }
3866 
3867 static void post_thread_start_event(const JavaThread* jt) {
3868   assert(jt != NULL, "invariant");
3869   EventThreadStart event;
3870   if (event.should_commit()) {
3871     event.set_thread(JFR_THREAD_ID(jt));
3872     event.commit();
3873   }
3874 }
3875 
3876 // Invocation API
3877 
3878 
3879 // Forward declaration
3880 extern const struct JNIInvokeInterface_ jni_InvokeInterface;
3881 
3882 // Global invocation API vars
3883 volatile int vm_created = 0;
3884 // Indicate whether it is safe to recreate VM
3885 volatile int safe_to_recreate_vm = 1;
3886 struct JavaVM_ main_vm = {&jni_InvokeInterface};
3887 
3888 
3889 #define JAVASTACKSIZE (400 * 1024)    /* Default size of a thread java stack */
3890 enum { VERIFY_NONE, VERIFY_REMOTE, VERIFY_ALL };
3891 
3892 DT_RETURN_MARK_DECL(GetDefaultJavaVMInitArgs, jint
3893                     , HOTSPOT_JNI_GETDEFAULTJAVAVMINITARGS_RETURN(_ret_ref));
3894 
3895 _JNI_IMPORT_OR_EXPORT_ jint JNICALL JNI_GetDefaultJavaVMInitArgs(void *args_) {
3896   HOTSPOT_JNI_GETDEFAULTJAVAVMINITARGS_ENTRY(args_);
3897   JDK1_1InitArgs *args = (JDK1_1InitArgs *)args_;
3898   jint ret = JNI_ERR;
3899   DT_RETURN_MARK(GetDefaultJavaVMInitArgs, jint, (const jint&)ret);
3900 
3901   if (Threads::is_supported_jni_version(args->version)) {
3902     ret = JNI_OK;
3903   }
3904   // 1.1 style no longer supported in hotspot.
3905   // According the JNI spec, we should update args->version on return.
3906   // We also use the structure to communicate with launcher about default
3907   // stack size.
3908   if (args->version == JNI_VERSION_1_1) {
3909     args->version = JNI_VERSION_1_2;
3910     // javaStackSize is int in arguments structure
3911     assert(jlong(ThreadStackSize) * K < INT_MAX, "integer overflow");
3912     args->javaStackSize = (jint)(ThreadStackSize * K);
3913   }
3914   return ret;
3915 }
3916 
3917 DT_RETURN_MARK_DECL(CreateJavaVM, jint
3918                     , HOTSPOT_JNI_CREATEJAVAVM_RETURN(_ret_ref));
3919 
3920 static jint JNI_CreateJavaVM_inner(JavaVM **vm, void **penv, void *args) {
3921   HOTSPOT_JNI_CREATEJAVAVM_ENTRY((void **) vm, penv, args);
3922 
3923   jint result = JNI_ERR;
3924   DT_RETURN_MARK(CreateJavaVM, jint, (const jint&)result);
3925 
3926   // We're about to use Atomic::xchg for synchronization.  Some Zero
3927   // platforms use the GCC builtin __sync_lock_test_and_set for this,
3928   // but __sync_lock_test_and_set is not guaranteed to do what we want
3929   // on all architectures.  So we check it works before relying on it.
3930 #if defined(ZERO) && defined(ASSERT)
3931   {
3932     jint a = 0xcafebabe;
3933     jint b = Atomic::xchg((jint) 0xdeadbeef, &a);
3934     void *c = &a;
3935     void *d = Atomic::xchg(&b, &c);
3936     assert(a == (jint) 0xdeadbeef && b == (jint) 0xcafebabe, "Atomic::xchg() works");
3937     assert(c == &b && d == &a, "Atomic::xchg() works");
3938   }
3939 #endif // ZERO && ASSERT
3940 
3941   // At the moment it's only possible to have one Java VM,
3942   // since some of the runtime state is in global variables.
3943 
3944   // We cannot use our mutex locks here, since they only work on
3945   // Threads. We do an atomic compare and exchange to ensure only
3946   // one thread can call this method at a time
3947 
3948   // We use Atomic::xchg rather than Atomic::add/dec since on some platforms
3949   // the add/dec implementations are dependent on whether we are running
3950   // on a multiprocessor Atomic::xchg does not have this problem.
3951   if (Atomic::xchg(1, &vm_created) == 1) {
3952     return JNI_EEXIST;   // already created, or create attempt in progress
3953   }
3954   if (Atomic::xchg(0, &safe_to_recreate_vm) == 0) {
3955     return JNI_ERR;  // someone tried and failed and retry not allowed.
3956   }
3957 
3958   assert(vm_created == 1, "vm_created is true during the creation");
3959 
3960   /**
3961    * Certain errors during initialization are recoverable and do not
3962    * prevent this method from being called again at a later time
3963    * (perhaps with different arguments).  However, at a certain
3964    * point during initialization if an error occurs we cannot allow
3965    * this function to be called again (or it will crash).  In those
3966    * situations, the 'canTryAgain' flag is set to false, which atomically
3967    * sets safe_to_recreate_vm to 1, such that any new call to
3968    * JNI_CreateJavaVM will immediately fail using the above logic.
3969    */
3970   bool can_try_again = true;
3971 
3972   result = Threads::create_vm((JavaVMInitArgs*) args, &can_try_again);
3973   if (result == JNI_OK) {
3974     JavaThread *thread = JavaThread::current();
3975     assert(!thread->has_pending_exception(), "should have returned not OK");
3976     /* thread is thread_in_vm here */
3977     *vm = (JavaVM *)(&main_vm);
3978     *(JNIEnv**)penv = thread->jni_environment();
3979 
3980 #if INCLUDE_JVMCI
3981     if (EnableJVMCI) {
3982       if (UseJVMCICompiler) {
3983         // JVMCI is initialized on a CompilerThread
3984         if (BootstrapJVMCI) {
3985           JavaThread* THREAD = thread;
3986           JVMCICompiler* compiler = JVMCICompiler::instance(true, CATCH);
3987           compiler->bootstrap(THREAD);
3988           if (HAS_PENDING_EXCEPTION) {
3989             HandleMark hm;
3990             vm_exit_during_initialization(Handle(THREAD, PENDING_EXCEPTION));
3991           }
3992         }
3993       }
3994     }
3995 #endif
3996 
3997     // Notify JVMTI
3998     if (JvmtiExport::should_post_thread_life()) {
3999        JvmtiExport::post_thread_start(thread);
4000     }
4001 
4002     post_thread_start_event(thread);
4003 
4004 #ifndef PRODUCT
4005     if (ReplayCompiles) ciReplay::replay(thread);
4006 
4007     // Some platforms (like Win*) need a wrapper around these test
4008     // functions in order to properly handle error conditions.
4009     VMError::test_error_handler();
4010 #endif
4011 
4012     // Since this is not a JVM_ENTRY we have to set the thread state manually before leaving.
4013     ThreadStateTransition::transition(thread, _thread_in_vm, _thread_in_native);
4014   } else {
4015     // If create_vm exits because of a pending exception, exit with that
4016     // exception.  In the future when we figure out how to reclaim memory,
4017     // we may be able to exit with JNI_ERR and allow the calling application
4018     // to continue.
4019     if (Universe::is_fully_initialized()) {
4020       // otherwise no pending exception possible - VM will already have aborted
4021       JavaThread* THREAD = JavaThread::current();
4022       if (HAS_PENDING_EXCEPTION) {
4023         HandleMark hm;
4024         vm_exit_during_initialization(Handle(THREAD, PENDING_EXCEPTION));
4025       }
4026     }
4027 
4028     if (can_try_again) {
4029       // reset safe_to_recreate_vm to 1 so that retrial would be possible
4030       safe_to_recreate_vm = 1;
4031     }
4032 
4033     // Creation failed. We must reset vm_created
4034     *vm = 0;
4035     *(JNIEnv**)penv = 0;
4036     // reset vm_created last to avoid race condition. Use OrderAccess to
4037     // control both compiler and architectural-based reordering.
4038     OrderAccess::release_store(&vm_created, 0);
4039   }
4040 
4041   // Flush stdout and stderr before exit.
4042   fflush(stdout);
4043   fflush(stderr);
4044 
4045   return result;
4046 
4047 }
4048 
4049 _JNI_IMPORT_OR_EXPORT_ jint JNICALL JNI_CreateJavaVM(JavaVM **vm, void **penv, void *args) {
4050   jint result = JNI_ERR;
4051   // On Windows, let CreateJavaVM run with SEH protection
4052 #ifdef _WIN32
4053   __try {
4054 #endif
4055     result = JNI_CreateJavaVM_inner(vm, penv, args);
4056 #ifdef _WIN32
4057   } __except(topLevelExceptionFilter((_EXCEPTION_POINTERS*)_exception_info())) {
4058     // Nothing to do.
4059   }
4060 #endif
4061   return result;
4062 }
4063 
4064 _JNI_IMPORT_OR_EXPORT_ jint JNICALL JNI_GetCreatedJavaVMs(JavaVM **vm_buf, jsize bufLen, jsize *numVMs) {
4065   // See bug 4367188, the wrapper can sometimes cause VM crashes
4066   // JNIWrapper("GetCreatedJavaVMs");
4067 
4068   HOTSPOT_JNI_GETCREATEDJAVAVMS_ENTRY((void **) vm_buf, bufLen, (uintptr_t *) numVMs);
4069 
4070   if (vm_created == 1) {
4071     if (numVMs != NULL) *numVMs = 1;
4072     if (bufLen > 0)     *vm_buf = (JavaVM *)(&main_vm);
4073   } else {
4074     if (numVMs != NULL) *numVMs = 0;
4075   }
4076   HOTSPOT_JNI_GETCREATEDJAVAVMS_RETURN(JNI_OK);
4077   return JNI_OK;
4078 }
4079 
4080 extern "C" {
4081 
4082 DT_RETURN_MARK_DECL(DestroyJavaVM, jint
4083                     , HOTSPOT_JNI_DESTROYJAVAVM_RETURN(_ret_ref));
4084 
4085 static jint JNICALL jni_DestroyJavaVM_inner(JavaVM *vm) {
4086   HOTSPOT_JNI_DESTROYJAVAVM_ENTRY(vm);
4087   jint res = JNI_ERR;
4088   DT_RETURN_MARK(DestroyJavaVM, jint, (const jint&)res);
4089 
4090   if (vm_created == 0) {
4091     res = JNI_ERR;
4092     return res;
4093   }
4094 
4095   JNIWrapper("DestroyJavaVM");
4096   JNIEnv *env;
4097   JavaVMAttachArgs destroyargs;
4098   destroyargs.version = CurrentVersion;
4099   destroyargs.name = (char *)"DestroyJavaVM";
4100   destroyargs.group = NULL;
4101   res = vm->AttachCurrentThread((void **)&env, (void *)&destroyargs);
4102   if (res != JNI_OK) {
4103     return res;
4104   }
4105 
4106   // Since this is not a JVM_ENTRY we have to set the thread state manually before entering.
4107   JavaThread* thread = JavaThread::current();
4108   ThreadStateTransition::transition_from_native(thread, _thread_in_vm);
4109   if (Threads::destroy_vm()) {
4110     // Should not change thread state, VM is gone
4111     vm_created = 0;
4112     res = JNI_OK;
4113     return res;
4114   } else {
4115     ThreadStateTransition::transition(thread, _thread_in_vm, _thread_in_native);
4116     res = JNI_ERR;
4117     return res;
4118   }
4119 }
4120 
4121 jint JNICALL jni_DestroyJavaVM(JavaVM *vm) {
4122   jint result = JNI_ERR;
4123   // On Windows, we need SEH protection
4124 #ifdef _WIN32
4125   __try {
4126 #endif
4127     result = jni_DestroyJavaVM_inner(vm);
4128 #ifdef _WIN32
4129   } __except(topLevelExceptionFilter((_EXCEPTION_POINTERS*)_exception_info())) {
4130     // Nothing to do.
4131   }
4132 #endif
4133   return result;
4134 }
4135 
4136 static jint attach_current_thread(JavaVM *vm, void **penv, void *_args, bool daemon) {
4137   JavaVMAttachArgs *args = (JavaVMAttachArgs *) _args;
4138 
4139   // Check below commented out from JDK1.2fcs as well
4140   /*
4141   if (args && (args->version != JNI_VERSION_1_1 || args->version != JNI_VERSION_1_2)) {
4142     return JNI_EVERSION;
4143   }
4144   */
4145 
4146   Thread* t = Thread::current_or_null();
4147   if (t != NULL) {
4148     // If the thread has been attached this operation is a no-op
4149     *(JNIEnv**)penv = ((JavaThread*) t)->jni_environment();
4150     return JNI_OK;
4151   }
4152 
4153   // Create a thread and mark it as attaching so it will be skipped by the
4154   // ThreadsListEnumerator - see CR 6404306
4155   JavaThread* thread = new JavaThread(true);
4156 
4157   // Set correct safepoint info. The thread is going to call into Java when
4158   // initializing the Java level thread object. Hence, the correct state must
4159   // be set in order for the Safepoint code to deal with it correctly.
4160   thread->set_thread_state(_thread_in_vm);
4161   thread->record_stack_base_and_size();
4162   thread->register_thread_stack_with_NMT();
4163   thread->initialize_thread_current();
4164 
4165   if (!os::create_attached_thread(thread)) {
4166     thread->smr_delete();
4167     return JNI_ERR;
4168   }
4169   // Enable stack overflow checks
4170   thread->create_stack_guard_pages();
4171 
4172   thread->initialize_tlab();
4173 
4174   thread->cache_global_variables();
4175 
4176   // This thread will not do a safepoint check, since it has
4177   // not been added to the Thread list yet.
4178   { MutexLocker ml(Threads_lock);
4179     // This must be inside this lock in order to get FullGCALot to work properly, i.e., to
4180     // avoid this thread trying to do a GC before it is added to the thread-list
4181     thread->set_active_handles(JNIHandleBlock::allocate_block());
4182     Threads::add(thread, daemon);
4183   }
4184   // Create thread group and name info from attach arguments
4185   oop group = NULL;
4186   char* thread_name = NULL;
4187   if (args != NULL && Threads::is_supported_jni_version(args->version)) {
4188     group = JNIHandles::resolve(args->group);
4189     thread_name = args->name; // may be NULL
4190   }
4191   if (group == NULL) group = Universe::main_thread_group();
4192 
4193   // Create Java level thread object and attach it to this thread
4194   bool attach_failed = false;
4195   {
4196     EXCEPTION_MARK;
4197     HandleMark hm(THREAD);
4198     Handle thread_group(THREAD, group);
4199     thread->allocate_threadObj(thread_group, thread_name, daemon, THREAD);
4200     if (HAS_PENDING_EXCEPTION) {
4201       CLEAR_PENDING_EXCEPTION;
4202       // cleanup outside the handle mark.
4203       attach_failed = true;
4204     }
4205   }
4206 
4207   if (attach_failed) {
4208     // Added missing cleanup
4209     thread->cleanup_failed_attach_current_thread(daemon);
4210     return JNI_ERR;
4211   }
4212 
4213   // mark the thread as no longer attaching
4214   // this uses a fence to push the change through so we don't have
4215   // to regrab the threads_lock
4216   thread->set_done_attaching_via_jni();
4217 
4218   // Set java thread status.
4219   java_lang_Thread::set_thread_status(thread->threadObj(),
4220               java_lang_Thread::RUNNABLE);
4221 
4222   // Notify the debugger
4223   if (JvmtiExport::should_post_thread_life()) {
4224     JvmtiExport::post_thread_start(thread);
4225   }
4226 
4227   post_thread_start_event(thread);
4228 
4229   *(JNIEnv**)penv = thread->jni_environment();
4230 
4231   // Now leaving the VM, so change thread_state. This is normally automatically taken care
4232   // of in the JVM_ENTRY. But in this situation we have to do it manually. Notice, that by
4233   // using ThreadStateTransition::transition, we do a callback to the safepoint code if
4234   // needed.
4235 
4236   ThreadStateTransition::transition(thread, _thread_in_vm, _thread_in_native);
4237 
4238   // Perform any platform dependent FPU setup
4239   os::setup_fpu();
4240 
4241   return JNI_OK;
4242 }
4243 
4244 
4245 jint JNICALL jni_AttachCurrentThread(JavaVM *vm, void **penv, void *_args) {
4246   HOTSPOT_JNI_ATTACHCURRENTTHREAD_ENTRY(vm, penv, _args);
4247   if (vm_created == 0) {
4248   HOTSPOT_JNI_ATTACHCURRENTTHREAD_RETURN((uint32_t) JNI_ERR);
4249     return JNI_ERR;
4250   }
4251 
4252   JNIWrapper("AttachCurrentThread");
4253   jint ret = attach_current_thread(vm, penv, _args, false);
4254   HOTSPOT_JNI_ATTACHCURRENTTHREAD_RETURN(ret);
4255   return ret;
4256 }
4257 
4258 
4259 jint JNICALL jni_DetachCurrentThread(JavaVM *vm)  {
4260   HOTSPOT_JNI_DETACHCURRENTTHREAD_ENTRY(vm);
4261 
4262   JNIWrapper("DetachCurrentThread");
4263 
4264   // If the thread has already been detached the operation is a no-op
4265   if (Thread::current_or_null() == NULL) {
4266     HOTSPOT_JNI_DETACHCURRENTTHREAD_RETURN(JNI_OK);
4267     return JNI_OK;
4268   }
4269 
4270   VM_Exit::block_if_vm_exited();
4271 
4272   JavaThread* thread = JavaThread::current();
4273   if (thread->has_last_Java_frame()) {
4274     HOTSPOT_JNI_DETACHCURRENTTHREAD_RETURN((uint32_t) JNI_ERR);
4275     // Can't detach a thread that's running java, that can't work.
4276     return JNI_ERR;
4277   }
4278 
4279   // Safepoint support. Have to do call-back to safepoint code, if in the
4280   // middle of a safepoint operation
4281   ThreadStateTransition::transition_from_native(thread, _thread_in_vm);
4282 
4283   // XXX: Note that JavaThread::exit() call below removes the guards on the
4284   // stack pages set up via enable_stack_{red,yellow}_zone() calls
4285   // above in jni_AttachCurrentThread. Unfortunately, while the setting
4286   // of the guards is visible in jni_AttachCurrentThread above,
4287   // the removal of the guards is buried below in JavaThread::exit()
4288   // here. The abstraction should be more symmetrically either exposed
4289   // or hidden (e.g. it could probably be hidden in the same
4290   // (platform-dependent) methods where we do alternate stack
4291   // maintenance work?)
4292   thread->exit(false, JavaThread::jni_detach);
4293   thread->smr_delete();
4294 
4295   HOTSPOT_JNI_DETACHCURRENTTHREAD_RETURN(JNI_OK);
4296   return JNI_OK;
4297 }
4298 
4299 DT_RETURN_MARK_DECL(GetEnv, jint
4300                     , HOTSPOT_JNI_GETENV_RETURN(_ret_ref));
4301 
4302 jint JNICALL jni_GetEnv(JavaVM *vm, void **penv, jint version) {
4303   HOTSPOT_JNI_GETENV_ENTRY(vm, penv, version);
4304   jint ret = JNI_ERR;
4305   DT_RETURN_MARK(GetEnv, jint, (const jint&)ret);
4306 
4307   if (vm_created == 0) {
4308     *penv = NULL;
4309     ret = JNI_EDETACHED;
4310     return ret;
4311   }
4312 
4313   if (JniExportedInterface::GetExportedInterface(vm, penv, version, &ret)) {
4314     return ret;
4315   }
4316 
4317 #ifndef JVMPI_VERSION_1
4318 // need these in order to be polite about older agents
4319 #define JVMPI_VERSION_1   ((jint)0x10000001)
4320 #define JVMPI_VERSION_1_1 ((jint)0x10000002)
4321 #define JVMPI_VERSION_1_2 ((jint)0x10000003)
4322 #endif // !JVMPI_VERSION_1
4323 
4324   Thread* thread = Thread::current_or_null();
4325   if (thread != NULL && thread->is_Java_thread()) {
4326     if (Threads::is_supported_jni_version_including_1_1(version)) {
4327       *(JNIEnv**)penv = ((JavaThread*) thread)->jni_environment();
4328       ret = JNI_OK;
4329       return ret;
4330 
4331     } else if (version == JVMPI_VERSION_1 ||
4332                version == JVMPI_VERSION_1_1 ||
4333                version == JVMPI_VERSION_1_2) {
4334       tty->print_cr("ERROR: JVMPI, an experimental interface, is no longer supported.");
4335       tty->print_cr("Please use the supported interface: the JVM Tool Interface (JVM TI).");
4336       ret = JNI_EVERSION;
4337       return ret;
4338     } else if (JvmtiExport::is_jvmdi_version(version)) {
4339       tty->print_cr("FATAL ERROR: JVMDI is no longer supported.");
4340       tty->print_cr("Please use the supported interface: the JVM Tool Interface (JVM TI).");
4341       ret = JNI_EVERSION;
4342       return ret;
4343     } else {
4344       *penv = NULL;
4345       ret = JNI_EVERSION;
4346       return ret;
4347     }
4348   } else {
4349     *penv = NULL;
4350     ret = JNI_EDETACHED;
4351     return ret;
4352   }
4353 }
4354 
4355 
4356 jint JNICALL jni_AttachCurrentThreadAsDaemon(JavaVM *vm, void **penv, void *_args) {
4357   HOTSPOT_JNI_ATTACHCURRENTTHREADASDAEMON_ENTRY(vm, penv, _args);
4358   if (vm_created == 0) {
4359   HOTSPOT_JNI_ATTACHCURRENTTHREADASDAEMON_RETURN((uint32_t) JNI_ERR);
4360     return JNI_ERR;
4361   }
4362 
4363   JNIWrapper("AttachCurrentThreadAsDaemon");
4364   jint ret = attach_current_thread(vm, penv, _args, true);
4365   HOTSPOT_JNI_ATTACHCURRENTTHREADASDAEMON_RETURN(ret);
4366   return ret;
4367 }
4368 
4369 
4370 } // End extern "C"
4371 
4372 const struct JNIInvokeInterface_ jni_InvokeInterface = {
4373     NULL,
4374     NULL,
4375     NULL,
4376 
4377     jni_DestroyJavaVM,
4378     jni_AttachCurrentThread,
4379     jni_DetachCurrentThread,
4380     jni_GetEnv,
4381     jni_AttachCurrentThreadAsDaemon
4382 };
--- EOF ---