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