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