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