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