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