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