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