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