unsafe.cpp revision 7426:0f6100dde08e
1/*
2 * Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25#include "precompiled.hpp"
26#include "classfile/vmSymbols.hpp"
27#include "memory/allocation.inline.hpp"
28#include "prims/jni.h"
29#include "prims/jvm.h"
30#include "runtime/atomic.inline.hpp"
31#include "runtime/globals.hpp"
32#include "runtime/interfaceSupport.hpp"
33#include "runtime/prefetch.inline.hpp"
34#include "runtime/orderAccess.inline.hpp"
35#include "runtime/reflection.hpp"
36#include "runtime/synchronizer.hpp"
37#include "runtime/vm_version.hpp"
38#include "services/threadService.hpp"
39#include "trace/tracing.hpp"
40#include "utilities/copy.hpp"
41#include "utilities/dtrace.hpp"
42#include "utilities/macros.hpp"
43#if INCLUDE_ALL_GCS
44#include "gc_implementation/g1/g1SATBCardTableModRefBS.hpp"
45#endif // INCLUDE_ALL_GCS
46
47PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
48
49/*
50 *      Implementation of class sun.misc.Unsafe
51 */
52
53
54#define MAX_OBJECT_SIZE \
55  ( arrayOopDesc::header_size(T_DOUBLE) * HeapWordSize \
56    + ((julong)max_jint * sizeof(double)) )
57
58
59#define UNSAFE_ENTRY(result_type, header) \
60  JVM_ENTRY(result_type, header)
61
62// Can't use UNSAFE_LEAF because it has the signature of a straight
63// call into the runtime (just like JVM_LEAF, funny that) but it's
64// called like a Java Native and thus the wrapper built for it passes
65// arguments like a JNI call.  It expects those arguments to be popped
66// from the stack on Intel like all good JNI args are, and adjusts the
67// stack according.  Since the JVM_LEAF call expects no extra
68// arguments the stack isn't popped in the C code, is pushed by the
69// wrapper and we get sick.
70//#define UNSAFE_LEAF(result_type, header) \
71//  JVM_LEAF(result_type, header)
72
73#define UNSAFE_END JVM_END
74
75#define UnsafeWrapper(arg) /*nothing, for the present*/
76
77
78inline void* addr_from_java(jlong addr) {
79  // This assert fails in a variety of ways on 32-bit systems.
80  // It is impossible to predict whether native code that converts
81  // pointers to longs will sign-extend or zero-extend the addresses.
82  //assert(addr == (uintptr_t)addr, "must not be odd high bits");
83  return (void*)(uintptr_t)addr;
84}
85
86inline jlong addr_to_java(void* p) {
87  assert(p == (void*)(uintptr_t)p, "must not be odd high bits");
88  return (uintptr_t)p;
89}
90
91
92// Note: The VM's obj_field and related accessors use byte-scaled
93// ("unscaled") offsets, just as the unsafe methods do.
94
95// However, the method Unsafe.fieldOffset explicitly declines to
96// guarantee this.  The field offset values manipulated by the Java user
97// through the Unsafe API are opaque cookies that just happen to be byte
98// offsets.  We represent this state of affairs by passing the cookies
99// through conversion functions when going between the VM and the Unsafe API.
100// The conversion functions just happen to be no-ops at present.
101
102inline jlong field_offset_to_byte_offset(jlong field_offset) {
103  return field_offset;
104}
105
106inline jlong field_offset_from_byte_offset(jlong byte_offset) {
107  return byte_offset;
108}
109
110inline jint invocation_key_from_method_slot(jint slot) {
111  return slot;
112}
113
114inline jint invocation_key_to_method_slot(jint key) {
115  return key;
116}
117
118inline void* index_oop_from_field_offset_long(oop p, jlong field_offset) {
119  jlong byte_offset = field_offset_to_byte_offset(field_offset);
120#ifdef ASSERT
121  if (p != NULL) {
122    assert(byte_offset >= 0 && byte_offset <= (jlong)MAX_OBJECT_SIZE, "sane offset");
123    if (byte_offset == (jint)byte_offset) {
124      void* ptr_plus_disp = (address)p + byte_offset;
125      assert((void*)p->obj_field_addr<oop>((jint)byte_offset) == ptr_plus_disp,
126             "raw [ptr+disp] must be consistent with oop::field_base");
127    }
128    jlong p_size = HeapWordSize * (jlong)(p->size());
129    assert(byte_offset < p_size, err_msg("Unsafe access: offset " INT64_FORMAT " > object's size " INT64_FORMAT, byte_offset, p_size));
130  }
131#endif
132  if (sizeof(char*) == sizeof(jint))    // (this constant folds!)
133    return (address)p + (jint) byte_offset;
134  else
135    return (address)p +        byte_offset;
136}
137
138// Externally callable versions:
139// (Use these in compiler intrinsics which emulate unsafe primitives.)
140jlong Unsafe_field_offset_to_byte_offset(jlong field_offset) {
141  return field_offset;
142}
143jlong Unsafe_field_offset_from_byte_offset(jlong byte_offset) {
144  return byte_offset;
145}
146jint Unsafe_invocation_key_from_method_slot(jint slot) {
147  return invocation_key_from_method_slot(slot);
148}
149jint Unsafe_invocation_key_to_method_slot(jint key) {
150  return invocation_key_to_method_slot(key);
151}
152
153
154///// Data in the Java heap.
155
156#define GET_FIELD(obj, offset, type_name, v) \
157  oop p = JNIHandles::resolve(obj); \
158  type_name v = *(type_name*)index_oop_from_field_offset_long(p, offset)
159
160#define SET_FIELD(obj, offset, type_name, x) \
161  oop p = JNIHandles::resolve(obj); \
162  *(type_name*)index_oop_from_field_offset_long(p, offset) = x
163
164#define GET_FIELD_VOLATILE(obj, offset, type_name, v) \
165  oop p = JNIHandles::resolve(obj); \
166  if (support_IRIW_for_not_multiple_copy_atomic_cpu) { \
167    OrderAccess::fence(); \
168  } \
169  volatile type_name v = OrderAccess::load_acquire((volatile type_name*)index_oop_from_field_offset_long(p, offset));
170
171#define SET_FIELD_VOLATILE(obj, offset, type_name, x) \
172  oop p = JNIHandles::resolve(obj); \
173  OrderAccess::release_store_fence((volatile type_name*)index_oop_from_field_offset_long(p, offset), x);
174
175// Macros for oops that check UseCompressedOops
176
177#define GET_OOP_FIELD(obj, offset, v) \
178  oop p = JNIHandles::resolve(obj);   \
179  oop v;                              \
180  if (UseCompressedOops) {            \
181    narrowOop n = *(narrowOop*)index_oop_from_field_offset_long(p, offset); \
182    v = oopDesc::decode_heap_oop(n);                                \
183  } else {                            \
184    v = *(oop*)index_oop_from_field_offset_long(p, offset);                 \
185  }
186
187
188// Get/SetObject must be special-cased, since it works with handles.
189
190// These functions allow a null base pointer with an arbitrary address.
191// But if the base pointer is non-null, the offset should make some sense.
192// That is, it should be in the range [0, MAX_OBJECT_SIZE].
193UNSAFE_ENTRY(jobject, Unsafe_GetObject(JNIEnv *env, jobject unsafe, jobject obj, jlong offset))
194  UnsafeWrapper("Unsafe_GetObject");
195  GET_OOP_FIELD(obj, offset, v)
196  jobject ret = JNIHandles::make_local(env, v);
197#if INCLUDE_ALL_GCS
198  // We could be accessing the referent field in a reference
199  // object. If G1 is enabled then we need to register non-null
200  // referent with the SATB barrier.
201  if (UseG1GC) {
202    bool needs_barrier = false;
203
204    if (ret != NULL) {
205      if (offset == java_lang_ref_Reference::referent_offset && obj != NULL) {
206        oop o = JNIHandles::resolve(obj);
207        Klass* k = o->klass();
208        if (InstanceKlass::cast(k)->reference_type() != REF_NONE) {
209          assert(InstanceKlass::cast(k)->is_subclass_of(SystemDictionary::Reference_klass()), "sanity");
210          needs_barrier = true;
211        }
212      }
213    }
214
215    if (needs_barrier) {
216      oop referent = JNIHandles::resolve(ret);
217      G1SATBCardTableModRefBS::enqueue(referent);
218    }
219  }
220#endif // INCLUDE_ALL_GCS
221  return ret;
222UNSAFE_END
223
224UNSAFE_ENTRY(void, Unsafe_SetObject(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jobject x_h))
225  UnsafeWrapper("Unsafe_SetObject");
226  oop x = JNIHandles::resolve(x_h);
227  oop p = JNIHandles::resolve(obj);
228  if (UseCompressedOops) {
229    oop_store((narrowOop*)index_oop_from_field_offset_long(p, offset), x);
230  } else {
231    oop_store((oop*)index_oop_from_field_offset_long(p, offset), x);
232  }
233UNSAFE_END
234
235UNSAFE_ENTRY(jobject, Unsafe_GetObjectVolatile(JNIEnv *env, jobject unsafe, jobject obj, jlong offset))
236  UnsafeWrapper("Unsafe_GetObjectVolatile");
237  oop p = JNIHandles::resolve(obj);
238  void* addr = index_oop_from_field_offset_long(p, offset);
239  volatile oop v;
240  if (UseCompressedOops) {
241    volatile narrowOop n = *(volatile narrowOop*) addr;
242    (void)const_cast<oop&>(v = oopDesc::decode_heap_oop(n));
243  } else {
244    (void)const_cast<oop&>(v = *(volatile oop*) addr);
245  }
246  OrderAccess::acquire();
247  return JNIHandles::make_local(env, v);
248UNSAFE_END
249
250UNSAFE_ENTRY(void, Unsafe_SetObjectVolatile(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jobject x_h))
251  UnsafeWrapper("Unsafe_SetObjectVolatile");
252  oop x = JNIHandles::resolve(x_h);
253  oop p = JNIHandles::resolve(obj);
254  void* addr = index_oop_from_field_offset_long(p, offset);
255  OrderAccess::release();
256  if (UseCompressedOops) {
257    oop_store((narrowOop*)addr, x);
258  } else {
259    oop_store((oop*)addr, x);
260  }
261  OrderAccess::fence();
262UNSAFE_END
263
264#ifndef SUPPORTS_NATIVE_CX8
265// Keep old code for platforms which may not have atomic jlong (8 bytes) instructions
266
267// Volatile long versions must use locks if !VM_Version::supports_cx8().
268// support_cx8 is a surrogate for 'supports atomic long memory ops'.
269
270UNSAFE_ENTRY(jlong, Unsafe_GetLongVolatile(JNIEnv *env, jobject unsafe, jobject obj, jlong offset))
271  UnsafeWrapper("Unsafe_GetLongVolatile");
272  {
273    if (VM_Version::supports_cx8()) {
274      GET_FIELD_VOLATILE(obj, offset, jlong, v);
275      return v;
276    }
277    else {
278      Handle p (THREAD, JNIHandles::resolve(obj));
279      jlong* addr = (jlong*)(index_oop_from_field_offset_long(p(), offset));
280      ObjectLocker ol(p, THREAD);
281      jlong value = *addr;
282      return value;
283    }
284  }
285UNSAFE_END
286
287UNSAFE_ENTRY(void, Unsafe_SetLongVolatile(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jlong x))
288  UnsafeWrapper("Unsafe_SetLongVolatile");
289  {
290    if (VM_Version::supports_cx8()) {
291      SET_FIELD_VOLATILE(obj, offset, jlong, x);
292    }
293    else {
294      Handle p (THREAD, JNIHandles::resolve(obj));
295      jlong* addr = (jlong*)(index_oop_from_field_offset_long(p(), offset));
296      ObjectLocker ol(p, THREAD);
297      *addr = x;
298    }
299  }
300UNSAFE_END
301
302#endif // not SUPPORTS_NATIVE_CX8
303
304#define DEFINE_GETSETOOP(jboolean, Boolean) \
305 \
306UNSAFE_ENTRY(jboolean, Unsafe_Get##Boolean##140(JNIEnv *env, jobject unsafe, jobject obj, jint offset)) \
307  UnsafeWrapper("Unsafe_Get"#Boolean); \
308  if (obj == NULL)  THROW_0(vmSymbols::java_lang_NullPointerException()); \
309  GET_FIELD(obj, offset, jboolean, v); \
310  return v; \
311UNSAFE_END \
312 \
313UNSAFE_ENTRY(void, Unsafe_Set##Boolean##140(JNIEnv *env, jobject unsafe, jobject obj, jint offset, jboolean x)) \
314  UnsafeWrapper("Unsafe_Set"#Boolean); \
315  if (obj == NULL)  THROW(vmSymbols::java_lang_NullPointerException()); \
316  SET_FIELD(obj, offset, jboolean, x); \
317UNSAFE_END \
318 \
319UNSAFE_ENTRY(jboolean, Unsafe_Get##Boolean(JNIEnv *env, jobject unsafe, jobject obj, jlong offset)) \
320  UnsafeWrapper("Unsafe_Get"#Boolean); \
321  GET_FIELD(obj, offset, jboolean, v); \
322  return v; \
323UNSAFE_END \
324 \
325UNSAFE_ENTRY(void, Unsafe_Set##Boolean(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jboolean x)) \
326  UnsafeWrapper("Unsafe_Set"#Boolean); \
327  SET_FIELD(obj, offset, jboolean, x); \
328UNSAFE_END \
329 \
330// END DEFINE_GETSETOOP.
331
332DEFINE_GETSETOOP(jboolean, Boolean)
333DEFINE_GETSETOOP(jbyte, Byte)
334DEFINE_GETSETOOP(jshort, Short);
335DEFINE_GETSETOOP(jchar, Char);
336DEFINE_GETSETOOP(jint, Int);
337DEFINE_GETSETOOP(jlong, Long);
338DEFINE_GETSETOOP(jfloat, Float);
339DEFINE_GETSETOOP(jdouble, Double);
340
341#undef DEFINE_GETSETOOP
342
343#define DEFINE_GETSETOOP_VOLATILE(jboolean, Boolean) \
344 \
345UNSAFE_ENTRY(jboolean, Unsafe_Get##Boolean##Volatile(JNIEnv *env, jobject unsafe, jobject obj, jlong offset)) \
346  UnsafeWrapper("Unsafe_Get"#Boolean); \
347  GET_FIELD_VOLATILE(obj, offset, jboolean, v); \
348  return v; \
349UNSAFE_END \
350 \
351UNSAFE_ENTRY(void, Unsafe_Set##Boolean##Volatile(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jboolean x)) \
352  UnsafeWrapper("Unsafe_Set"#Boolean); \
353  SET_FIELD_VOLATILE(obj, offset, jboolean, x); \
354UNSAFE_END \
355 \
356// END DEFINE_GETSETOOP_VOLATILE.
357
358DEFINE_GETSETOOP_VOLATILE(jboolean, Boolean)
359DEFINE_GETSETOOP_VOLATILE(jbyte, Byte)
360DEFINE_GETSETOOP_VOLATILE(jshort, Short);
361DEFINE_GETSETOOP_VOLATILE(jchar, Char);
362DEFINE_GETSETOOP_VOLATILE(jint, Int);
363DEFINE_GETSETOOP_VOLATILE(jfloat, Float);
364DEFINE_GETSETOOP_VOLATILE(jdouble, Double);
365
366#ifdef SUPPORTS_NATIVE_CX8
367DEFINE_GETSETOOP_VOLATILE(jlong, Long);
368#endif
369
370#undef DEFINE_GETSETOOP_VOLATILE
371
372// The non-intrinsified versions of setOrdered just use setVolatile
373
374UNSAFE_ENTRY(void, Unsafe_SetOrderedInt(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jint x))
375  UnsafeWrapper("Unsafe_SetOrderedInt");
376  SET_FIELD_VOLATILE(obj, offset, jint, x);
377UNSAFE_END
378
379UNSAFE_ENTRY(void, Unsafe_SetOrderedObject(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jobject x_h))
380  UnsafeWrapper("Unsafe_SetOrderedObject");
381  oop x = JNIHandles::resolve(x_h);
382  oop p = JNIHandles::resolve(obj);
383  void* addr = index_oop_from_field_offset_long(p, offset);
384  OrderAccess::release();
385  if (UseCompressedOops) {
386    oop_store((narrowOop*)addr, x);
387  } else {
388    oop_store((oop*)addr, x);
389  }
390  OrderAccess::fence();
391UNSAFE_END
392
393UNSAFE_ENTRY(void, Unsafe_SetOrderedLong(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jlong x))
394  UnsafeWrapper("Unsafe_SetOrderedLong");
395#ifdef SUPPORTS_NATIVE_CX8
396  SET_FIELD_VOLATILE(obj, offset, jlong, x);
397#else
398  // Keep old code for platforms which may not have atomic long (8 bytes) instructions
399  {
400    if (VM_Version::supports_cx8()) {
401      SET_FIELD_VOLATILE(obj, offset, jlong, x);
402    }
403    else {
404      Handle p (THREAD, JNIHandles::resolve(obj));
405      jlong* addr = (jlong*)(index_oop_from_field_offset_long(p(), offset));
406      ObjectLocker ol(p, THREAD);
407      *addr = x;
408    }
409  }
410#endif
411UNSAFE_END
412
413UNSAFE_ENTRY(void, Unsafe_LoadFence(JNIEnv *env, jobject unsafe))
414  UnsafeWrapper("Unsafe_LoadFence");
415  OrderAccess::acquire();
416UNSAFE_END
417
418UNSAFE_ENTRY(void, Unsafe_StoreFence(JNIEnv *env, jobject unsafe))
419  UnsafeWrapper("Unsafe_StoreFence");
420  OrderAccess::release();
421UNSAFE_END
422
423UNSAFE_ENTRY(void, Unsafe_FullFence(JNIEnv *env, jobject unsafe))
424  UnsafeWrapper("Unsafe_FullFence");
425  OrderAccess::fence();
426UNSAFE_END
427
428////// Data in the C heap.
429
430// Note:  These do not throw NullPointerException for bad pointers.
431// They just crash.  Only a oop base pointer can generate a NullPointerException.
432//
433#define DEFINE_GETSETNATIVE(java_type, Type, native_type) \
434 \
435UNSAFE_ENTRY(java_type, Unsafe_GetNative##Type(JNIEnv *env, jobject unsafe, jlong addr)) \
436  UnsafeWrapper("Unsafe_GetNative"#Type); \
437  void* p = addr_from_java(addr); \
438  JavaThread* t = JavaThread::current(); \
439  t->set_doing_unsafe_access(true); \
440  java_type x = *(volatile native_type*)p; \
441  t->set_doing_unsafe_access(false); \
442  return x; \
443UNSAFE_END \
444 \
445UNSAFE_ENTRY(void, Unsafe_SetNative##Type(JNIEnv *env, jobject unsafe, jlong addr, java_type x)) \
446  UnsafeWrapper("Unsafe_SetNative"#Type); \
447  JavaThread* t = JavaThread::current(); \
448  t->set_doing_unsafe_access(true); \
449  void* p = addr_from_java(addr); \
450  *(volatile native_type*)p = x; \
451  t->set_doing_unsafe_access(false); \
452UNSAFE_END \
453 \
454// END DEFINE_GETSETNATIVE.
455
456DEFINE_GETSETNATIVE(jbyte, Byte, signed char)
457DEFINE_GETSETNATIVE(jshort, Short, signed short);
458DEFINE_GETSETNATIVE(jchar, Char, unsigned short);
459DEFINE_GETSETNATIVE(jint, Int, jint);
460// no long -- handled specially
461DEFINE_GETSETNATIVE(jfloat, Float, float);
462DEFINE_GETSETNATIVE(jdouble, Double, double);
463
464#undef DEFINE_GETSETNATIVE
465
466UNSAFE_ENTRY(jlong, Unsafe_GetNativeLong(JNIEnv *env, jobject unsafe, jlong addr))
467  UnsafeWrapper("Unsafe_GetNativeLong");
468  JavaThread* t = JavaThread::current();
469  // We do it this way to avoid problems with access to heap using 64
470  // bit loads, as jlong in heap could be not 64-bit aligned, and on
471  // some CPUs (SPARC) it leads to SIGBUS.
472  t->set_doing_unsafe_access(true);
473  void* p = addr_from_java(addr);
474  jlong x;
475  if (((intptr_t)p & 7) == 0) {
476    // jlong is aligned, do a volatile access
477    x = *(volatile jlong*)p;
478  } else {
479    jlong_accessor acc;
480    acc.words[0] = ((volatile jint*)p)[0];
481    acc.words[1] = ((volatile jint*)p)[1];
482    x = acc.long_value;
483  }
484  t->set_doing_unsafe_access(false);
485  return x;
486UNSAFE_END
487
488UNSAFE_ENTRY(void, Unsafe_SetNativeLong(JNIEnv *env, jobject unsafe, jlong addr, jlong x))
489  UnsafeWrapper("Unsafe_SetNativeLong");
490  JavaThread* t = JavaThread::current();
491  // see comment for Unsafe_GetNativeLong
492  t->set_doing_unsafe_access(true);
493  void* p = addr_from_java(addr);
494  if (((intptr_t)p & 7) == 0) {
495    // jlong is aligned, do a volatile access
496    *(volatile jlong*)p = x;
497  } else {
498    jlong_accessor acc;
499    acc.long_value = x;
500    ((volatile jint*)p)[0] = acc.words[0];
501    ((volatile jint*)p)[1] = acc.words[1];
502  }
503  t->set_doing_unsafe_access(false);
504UNSAFE_END
505
506
507UNSAFE_ENTRY(jlong, Unsafe_GetNativeAddress(JNIEnv *env, jobject unsafe, jlong addr))
508  UnsafeWrapper("Unsafe_GetNativeAddress");
509  void* p = addr_from_java(addr);
510  return addr_to_java(*(void**)p);
511UNSAFE_END
512
513UNSAFE_ENTRY(void, Unsafe_SetNativeAddress(JNIEnv *env, jobject unsafe, jlong addr, jlong x))
514  UnsafeWrapper("Unsafe_SetNativeAddress");
515  void* p = addr_from_java(addr);
516  *(void**)p = addr_from_java(x);
517UNSAFE_END
518
519
520////// Allocation requests
521
522UNSAFE_ENTRY(jobject, Unsafe_AllocateInstance(JNIEnv *env, jobject unsafe, jclass cls))
523  UnsafeWrapper("Unsafe_AllocateInstance");
524  {
525    ThreadToNativeFromVM ttnfv(thread);
526    return env->AllocObject(cls);
527  }
528UNSAFE_END
529
530UNSAFE_ENTRY(jlong, Unsafe_AllocateMemory(JNIEnv *env, jobject unsafe, jlong size))
531  UnsafeWrapper("Unsafe_AllocateMemory");
532  size_t sz = (size_t)size;
533  if (sz != (julong)size || size < 0) {
534    THROW_0(vmSymbols::java_lang_IllegalArgumentException());
535  }
536  if (sz == 0) {
537    return 0;
538  }
539  sz = round_to(sz, HeapWordSize);
540  void* x = os::malloc(sz, mtInternal);
541  if (x == NULL) {
542    THROW_0(vmSymbols::java_lang_OutOfMemoryError());
543  }
544  //Copy::fill_to_words((HeapWord*)x, sz / HeapWordSize);
545  return addr_to_java(x);
546UNSAFE_END
547
548UNSAFE_ENTRY(jlong, Unsafe_ReallocateMemory(JNIEnv *env, jobject unsafe, jlong addr, jlong size))
549  UnsafeWrapper("Unsafe_ReallocateMemory");
550  void* p = addr_from_java(addr);
551  size_t sz = (size_t)size;
552  if (sz != (julong)size || size < 0) {
553    THROW_0(vmSymbols::java_lang_IllegalArgumentException());
554  }
555  if (sz == 0) {
556    os::free(p);
557    return 0;
558  }
559  sz = round_to(sz, HeapWordSize);
560  void* x = (p == NULL) ? os::malloc(sz, mtInternal) : os::realloc(p, sz, mtInternal);
561  if (x == NULL) {
562    THROW_0(vmSymbols::java_lang_OutOfMemoryError());
563  }
564  return addr_to_java(x);
565UNSAFE_END
566
567UNSAFE_ENTRY(void, Unsafe_FreeMemory(JNIEnv *env, jobject unsafe, jlong addr))
568  UnsafeWrapper("Unsafe_FreeMemory");
569  void* p = addr_from_java(addr);
570  if (p == NULL) {
571    return;
572  }
573  os::free(p);
574UNSAFE_END
575
576UNSAFE_ENTRY(void, Unsafe_SetMemory(JNIEnv *env, jobject unsafe, jlong addr, jlong size, jbyte value))
577  UnsafeWrapper("Unsafe_SetMemory");
578  size_t sz = (size_t)size;
579  if (sz != (julong)size || size < 0) {
580    THROW(vmSymbols::java_lang_IllegalArgumentException());
581  }
582  char* p = (char*) addr_from_java(addr);
583  Copy::fill_to_memory_atomic(p, sz, value);
584UNSAFE_END
585
586UNSAFE_ENTRY(void, Unsafe_SetMemory2(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jlong size, jbyte value))
587  UnsafeWrapper("Unsafe_SetMemory");
588  size_t sz = (size_t)size;
589  if (sz != (julong)size || size < 0) {
590    THROW(vmSymbols::java_lang_IllegalArgumentException());
591  }
592  oop base = JNIHandles::resolve(obj);
593  void* p = index_oop_from_field_offset_long(base, offset);
594  Copy::fill_to_memory_atomic(p, sz, value);
595UNSAFE_END
596
597UNSAFE_ENTRY(void, Unsafe_CopyMemory(JNIEnv *env, jobject unsafe, jlong srcAddr, jlong dstAddr, jlong size))
598  UnsafeWrapper("Unsafe_CopyMemory");
599  if (size == 0) {
600    return;
601  }
602  size_t sz = (size_t)size;
603  if (sz != (julong)size || size < 0) {
604    THROW(vmSymbols::java_lang_IllegalArgumentException());
605  }
606  void* src = addr_from_java(srcAddr);
607  void* dst = addr_from_java(dstAddr);
608  Copy::conjoint_memory_atomic(src, dst, sz);
609UNSAFE_END
610
611UNSAFE_ENTRY(void, Unsafe_CopyMemory2(JNIEnv *env, jobject unsafe, jobject srcObj, jlong srcOffset, jobject dstObj, jlong dstOffset, jlong size))
612  UnsafeWrapper("Unsafe_CopyMemory");
613  if (size == 0) {
614    return;
615  }
616  size_t sz = (size_t)size;
617  if (sz != (julong)size || size < 0) {
618    THROW(vmSymbols::java_lang_IllegalArgumentException());
619  }
620  oop srcp = JNIHandles::resolve(srcObj);
621  oop dstp = JNIHandles::resolve(dstObj);
622  if (dstp != NULL && !dstp->is_typeArray()) {
623    // NYI:  This works only for non-oop arrays at present.
624    // Generalizing it would be reasonable, but requires card marking.
625    // Also, autoboxing a Long from 0L in copyMemory(x,y, 0L,z, n) would be bad.
626    THROW(vmSymbols::java_lang_IllegalArgumentException());
627  }
628  void* src = index_oop_from_field_offset_long(srcp, srcOffset);
629  void* dst = index_oop_from_field_offset_long(dstp, dstOffset);
630  Copy::conjoint_memory_atomic(src, dst, sz);
631UNSAFE_END
632
633
634////// Random queries
635
636// See comment at file start about UNSAFE_LEAF
637//UNSAFE_LEAF(jint, Unsafe_AddressSize())
638UNSAFE_ENTRY(jint, Unsafe_AddressSize(JNIEnv *env, jobject unsafe))
639  UnsafeWrapper("Unsafe_AddressSize");
640  return sizeof(void*);
641UNSAFE_END
642
643// See comment at file start about UNSAFE_LEAF
644//UNSAFE_LEAF(jint, Unsafe_PageSize())
645UNSAFE_ENTRY(jint, Unsafe_PageSize(JNIEnv *env, jobject unsafe))
646  UnsafeWrapper("Unsafe_PageSize");
647  return os::vm_page_size();
648UNSAFE_END
649
650jint find_field_offset(jobject field, int must_be_static, TRAPS) {
651  if (field == NULL) {
652    THROW_0(vmSymbols::java_lang_NullPointerException());
653  }
654
655  oop reflected   = JNIHandles::resolve_non_null(field);
656  oop mirror      = java_lang_reflect_Field::clazz(reflected);
657  Klass* k      = java_lang_Class::as_Klass(mirror);
658  int slot        = java_lang_reflect_Field::slot(reflected);
659  int modifiers   = java_lang_reflect_Field::modifiers(reflected);
660
661  if (must_be_static >= 0) {
662    int really_is_static = ((modifiers & JVM_ACC_STATIC) != 0);
663    if (must_be_static != really_is_static) {
664      THROW_0(vmSymbols::java_lang_IllegalArgumentException());
665    }
666  }
667
668  int offset = InstanceKlass::cast(k)->field_offset(slot);
669  return field_offset_from_byte_offset(offset);
670}
671
672UNSAFE_ENTRY(jlong, Unsafe_ObjectFieldOffset(JNIEnv *env, jobject unsafe, jobject field))
673  UnsafeWrapper("Unsafe_ObjectFieldOffset");
674  return find_field_offset(field, 0, THREAD);
675UNSAFE_END
676
677UNSAFE_ENTRY(jlong, Unsafe_StaticFieldOffset(JNIEnv *env, jobject unsafe, jobject field))
678  UnsafeWrapper("Unsafe_StaticFieldOffset");
679  return find_field_offset(field, 1, THREAD);
680UNSAFE_END
681
682UNSAFE_ENTRY(jobject, Unsafe_StaticFieldBaseFromField(JNIEnv *env, jobject unsafe, jobject field))
683  UnsafeWrapper("Unsafe_StaticFieldBase");
684  // Note:  In this VM implementation, a field address is always a short
685  // offset from the base of a a klass metaobject.  Thus, the full dynamic
686  // range of the return type is never used.  However, some implementations
687  // might put the static field inside an array shared by many classes,
688  // or even at a fixed address, in which case the address could be quite
689  // large.  In that last case, this function would return NULL, since
690  // the address would operate alone, without any base pointer.
691
692  if (field == NULL)  THROW_0(vmSymbols::java_lang_NullPointerException());
693
694  oop reflected   = JNIHandles::resolve_non_null(field);
695  oop mirror      = java_lang_reflect_Field::clazz(reflected);
696  int modifiers   = java_lang_reflect_Field::modifiers(reflected);
697
698  if ((modifiers & JVM_ACC_STATIC) == 0) {
699    THROW_0(vmSymbols::java_lang_IllegalArgumentException());
700  }
701
702  return JNIHandles::make_local(env, mirror);
703UNSAFE_END
704
705//@deprecated
706UNSAFE_ENTRY(jint, Unsafe_FieldOffset(JNIEnv *env, jobject unsafe, jobject field))
707  UnsafeWrapper("Unsafe_FieldOffset");
708  // tries (but fails) to be polymorphic between static and non-static:
709  jlong offset = find_field_offset(field, -1, THREAD);
710  guarantee(offset == (jint)offset, "offset fits in 32 bits");
711  return (jint)offset;
712UNSAFE_END
713
714//@deprecated
715UNSAFE_ENTRY(jobject, Unsafe_StaticFieldBaseFromClass(JNIEnv *env, jobject unsafe, jobject clazz))
716  UnsafeWrapper("Unsafe_StaticFieldBase");
717  if (clazz == NULL) {
718    THROW_0(vmSymbols::java_lang_NullPointerException());
719  }
720  return JNIHandles::make_local(env, JNIHandles::resolve_non_null(clazz));
721UNSAFE_END
722
723UNSAFE_ENTRY(void, Unsafe_EnsureClassInitialized(JNIEnv *env, jobject unsafe, jobject clazz)) {
724  UnsafeWrapper("Unsafe_EnsureClassInitialized");
725  if (clazz == NULL) {
726    THROW(vmSymbols::java_lang_NullPointerException());
727  }
728  oop mirror = JNIHandles::resolve_non_null(clazz);
729
730  Klass* klass = java_lang_Class::as_Klass(mirror);
731  if (klass != NULL && klass->should_be_initialized()) {
732    InstanceKlass* k = InstanceKlass::cast(klass);
733    k->initialize(CHECK);
734  }
735}
736UNSAFE_END
737
738UNSAFE_ENTRY(jboolean, Unsafe_ShouldBeInitialized(JNIEnv *env, jobject unsafe, jobject clazz)) {
739  UnsafeWrapper("Unsafe_ShouldBeInitialized");
740  if (clazz == NULL) {
741    THROW_(vmSymbols::java_lang_NullPointerException(), false);
742  }
743  oop mirror = JNIHandles::resolve_non_null(clazz);
744  Klass* klass = java_lang_Class::as_Klass(mirror);
745  if (klass != NULL && klass->should_be_initialized()) {
746    return true;
747  }
748  return false;
749}
750UNSAFE_END
751
752static void getBaseAndScale(int& base, int& scale, jclass acls, TRAPS) {
753  if (acls == NULL) {
754    THROW(vmSymbols::java_lang_NullPointerException());
755  }
756  oop      mirror = JNIHandles::resolve_non_null(acls);
757  Klass* k      = java_lang_Class::as_Klass(mirror);
758  if (k == NULL || !k->oop_is_array()) {
759    THROW(vmSymbols::java_lang_InvalidClassException());
760  } else if (k->oop_is_objArray()) {
761    base  = arrayOopDesc::base_offset_in_bytes(T_OBJECT);
762    scale = heapOopSize;
763  } else if (k->oop_is_typeArray()) {
764    TypeArrayKlass* tak = TypeArrayKlass::cast(k);
765    base  = tak->array_header_in_bytes();
766    assert(base == arrayOopDesc::base_offset_in_bytes(tak->element_type()), "array_header_size semantics ok");
767    scale = (1 << tak->log2_element_size());
768  } else {
769    ShouldNotReachHere();
770  }
771}
772
773UNSAFE_ENTRY(jint, Unsafe_ArrayBaseOffset(JNIEnv *env, jobject unsafe, jclass acls))
774  UnsafeWrapper("Unsafe_ArrayBaseOffset");
775  int base, scale;
776  getBaseAndScale(base, scale, acls, CHECK_0);
777  return field_offset_from_byte_offset(base);
778UNSAFE_END
779
780
781UNSAFE_ENTRY(jint, Unsafe_ArrayIndexScale(JNIEnv *env, jobject unsafe, jclass acls))
782  UnsafeWrapper("Unsafe_ArrayIndexScale");
783  int base, scale;
784  getBaseAndScale(base, scale, acls, CHECK_0);
785  // This VM packs both fields and array elements down to the byte.
786  // But watch out:  If this changes, so that array references for
787  // a given primitive type (say, T_BOOLEAN) use different memory units
788  // than fields, this method MUST return zero for such arrays.
789  // For example, the VM used to store sub-word sized fields in full
790  // words in the object layout, so that accessors like getByte(Object,int)
791  // did not really do what one might expect for arrays.  Therefore,
792  // this function used to report a zero scale factor, so that the user
793  // would know not to attempt to access sub-word array elements.
794  // // Code for unpacked fields:
795  // if (scale < wordSize)  return 0;
796
797  // The following allows for a pretty general fieldOffset cookie scheme,
798  // but requires it to be linear in byte offset.
799  return field_offset_from_byte_offset(scale) - field_offset_from_byte_offset(0);
800UNSAFE_END
801
802
803static inline void throw_new(JNIEnv *env, const char *ename) {
804  char buf[100];
805  jio_snprintf(buf, 100, "%s%s", "java/lang/", ename);
806  jclass cls = env->FindClass(buf);
807  if (env->ExceptionCheck()) {
808    env->ExceptionClear();
809    tty->print_cr("Unsafe: cannot throw %s because FindClass has failed", buf);
810    return;
811  }
812  char* msg = NULL;
813  env->ThrowNew(cls, msg);
814}
815
816static jclass Unsafe_DefineClass_impl(JNIEnv *env, jstring name, jbyteArray data, int offset, int length, jobject loader, jobject pd) {
817  {
818    // Code lifted from JDK 1.3 ClassLoader.c
819
820    jbyte *body;
821    char *utfName;
822    jclass result = 0;
823    char buf[128];
824
825    if (UsePerfData) {
826      ClassLoader::unsafe_defineClassCallCounter()->inc();
827    }
828
829    if (data == NULL) {
830        throw_new(env, "NullPointerException");
831        return 0;
832    }
833
834    /* Work around 4153825. malloc crashes on Solaris when passed a
835     * negative size.
836     */
837    if (length < 0) {
838        throw_new(env, "ArrayIndexOutOfBoundsException");
839        return 0;
840    }
841
842    body = NEW_C_HEAP_ARRAY(jbyte, length, mtInternal);
843
844    if (body == 0) {
845        throw_new(env, "OutOfMemoryError");
846        return 0;
847    }
848
849    env->GetByteArrayRegion(data, offset, length, body);
850
851    if (env->ExceptionOccurred())
852        goto free_body;
853
854    if (name != NULL) {
855        uint len = env->GetStringUTFLength(name);
856        int unicode_len = env->GetStringLength(name);
857        if (len >= sizeof(buf)) {
858            utfName = NEW_C_HEAP_ARRAY(char, len + 1, mtInternal);
859            if (utfName == NULL) {
860                throw_new(env, "OutOfMemoryError");
861                goto free_body;
862            }
863        } else {
864            utfName = buf;
865        }
866        env->GetStringUTFRegion(name, 0, unicode_len, utfName);
867        //VerifyFixClassname(utfName);
868        for (uint i = 0; i < len; i++) {
869          if (utfName[i] == '.')   utfName[i] = '/';
870        }
871    } else {
872        utfName = NULL;
873    }
874
875    result = JVM_DefineClass(env, utfName, loader, body, length, pd);
876
877    if (utfName && utfName != buf)
878        FREE_C_HEAP_ARRAY(char, utfName, mtInternal);
879
880 free_body:
881    FREE_C_HEAP_ARRAY(jbyte, body, mtInternal);
882    return result;
883  }
884}
885
886
887UNSAFE_ENTRY(jclass, Unsafe_DefineClass(JNIEnv *env, jobject unsafe, jstring name, jbyteArray data, int offset, int length, jobject loader, jobject pd))
888  UnsafeWrapper("Unsafe_DefineClass");
889  {
890    ThreadToNativeFromVM ttnfv(thread);
891    return Unsafe_DefineClass_impl(env, name, data, offset, length, loader, pd);
892  }
893UNSAFE_END
894
895static jobject get_class_loader(JNIEnv* env, jclass cls) {
896  if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(cls))) {
897    return NULL;
898  }
899  Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
900  oop loader = k->class_loader();
901  return JNIHandles::make_local(env, loader);
902}
903
904UNSAFE_ENTRY(jclass, Unsafe_DefineClass0(JNIEnv *env, jobject unsafe, jstring name, jbyteArray data, int offset, int length))
905  UnsafeWrapper("Unsafe_DefineClass");
906  {
907    ThreadToNativeFromVM ttnfv(thread);
908
909    int depthFromDefineClass0 = 1;
910    jclass  caller = JVM_GetCallerClass(env, depthFromDefineClass0);
911    jobject loader = (caller == NULL) ? NULL : get_class_loader(env, caller);
912    jobject pd     = (caller == NULL) ? NULL : JVM_GetProtectionDomain(env, caller);
913
914    return Unsafe_DefineClass_impl(env, name, data, offset, length, loader, pd);
915  }
916UNSAFE_END
917
918
919#define DAC_Args CLS"[B["OBJ
920// define a class but do not make it known to the class loader or system dictionary
921// - host_class:  supplies context for linkage, access control, protection domain, and class loader
922// - data:  bytes of a class file, a raw memory address (length gives the number of bytes)
923// - cp_patches:  where non-null entries exist, they replace corresponding CP entries in data
924
925// When you load an anonymous class U, it works as if you changed its name just before loading,
926// to a name that you will never use again.  Since the name is lost, no other class can directly
927// link to any member of U.  Just after U is loaded, the only way to use it is reflectively,
928// through java.lang.Class methods like Class.newInstance.
929
930// Access checks for linkage sites within U continue to follow the same rules as for named classes.
931// The package of an anonymous class is given by the package qualifier on the name under which it was loaded.
932// An anonymous class also has special privileges to access any member of its host class.
933// This is the main reason why this loading operation is unsafe.  The purpose of this is to
934// allow language implementations to simulate "open classes"; a host class in effect gets
935// new code when an anonymous class is loaded alongside it.  A less convenient but more
936// standard way to do this is with reflection, which can also be set to ignore access
937// restrictions.
938
939// Access into an anonymous class is possible only through reflection.  Therefore, there
940// are no special access rules for calling into an anonymous class.  The relaxed access
941// rule for the host class is applied in the opposite direction:  A host class reflectively
942// access one of its anonymous classes.
943
944// If you load the same bytecodes twice, you get two different classes.  You can reload
945// the same bytecodes with or without varying CP patches.
946
947// By using the CP patching array, you can have a new anonymous class U2 refer to an older one U1.
948// The bytecodes for U2 should refer to U1 by a symbolic name (doesn't matter what the name is).
949// The CONSTANT_Class entry for that name can be patched to refer directly to U1.
950
951// This allows, for example, U2 to use U1 as a superclass or super-interface, or as
952// an outer class (so that U2 is an anonymous inner class of anonymous U1).
953// It is not possible for a named class, or an older anonymous class, to refer by
954// name (via its CP) to a newer anonymous class.
955
956// CP patching may also be used to modify (i.e., hack) the names of methods, classes,
957// or type descriptors used in the loaded anonymous class.
958
959// Finally, CP patching may be used to introduce "live" objects into the constant pool,
960// instead of "dead" strings.  A compiled statement like println((Object)"hello") can
961// be changed to println(greeting), where greeting is an arbitrary object created before
962// the anonymous class is loaded.  This is useful in dynamic languages, in which
963// various kinds of metaobjects must be introduced as constants into bytecode.
964// Note the cast (Object), which tells the verifier to expect an arbitrary object,
965// not just a literal string.  For such ldc instructions, the verifier uses the
966// type Object instead of String, if the loaded constant is not in fact a String.
967
968static instanceKlassHandle
969Unsafe_DefineAnonymousClass_impl(JNIEnv *env,
970                                 jclass host_class, jbyteArray data, jobjectArray cp_patches_jh,
971                                 HeapWord* *temp_alloc,
972                                 TRAPS) {
973
974  if (UsePerfData) {
975    ClassLoader::unsafe_defineClassCallCounter()->inc();
976  }
977
978  if (data == NULL) {
979    THROW_0(vmSymbols::java_lang_NullPointerException());
980  }
981
982  jint length = typeArrayOop(JNIHandles::resolve_non_null(data))->length();
983  jint word_length = (length + sizeof(HeapWord)-1) / sizeof(HeapWord);
984  HeapWord* body = NEW_C_HEAP_ARRAY(HeapWord, word_length, mtInternal);
985  if (body == NULL) {
986    THROW_0(vmSymbols::java_lang_OutOfMemoryError());
987  }
988
989  // caller responsible to free it:
990  (*temp_alloc) = body;
991
992  {
993    jbyte* array_base = typeArrayOop(JNIHandles::resolve_non_null(data))->byte_at_addr(0);
994    Copy::conjoint_words((HeapWord*) array_base, body, word_length);
995  }
996
997  u1* class_bytes = (u1*) body;
998  int class_bytes_length = (int) length;
999  if (class_bytes_length < 0)  class_bytes_length = 0;
1000  if (class_bytes == NULL
1001      || host_class == NULL
1002      || length != class_bytes_length)
1003    THROW_0(vmSymbols::java_lang_IllegalArgumentException());
1004
1005  objArrayHandle cp_patches_h;
1006  if (cp_patches_jh != NULL) {
1007    oop p = JNIHandles::resolve_non_null(cp_patches_jh);
1008    if (!p->is_objArray())
1009      THROW_0(vmSymbols::java_lang_IllegalArgumentException());
1010    cp_patches_h = objArrayHandle(THREAD, (objArrayOop)p);
1011  }
1012
1013  KlassHandle host_klass(THREAD, java_lang_Class::as_Klass(JNIHandles::resolve_non_null(host_class)));
1014  const char* host_source = host_klass->external_name();
1015  Handle      host_loader(THREAD, host_klass->class_loader());
1016  Handle      host_domain(THREAD, host_klass->protection_domain());
1017
1018  GrowableArray<Handle>* cp_patches = NULL;
1019  if (cp_patches_h.not_null()) {
1020    int alen = cp_patches_h->length();
1021    for (int i = alen-1; i >= 0; i--) {
1022      oop p = cp_patches_h->obj_at(i);
1023      if (p != NULL) {
1024        Handle patch(THREAD, p);
1025        if (cp_patches == NULL)
1026          cp_patches = new GrowableArray<Handle>(i+1, i+1, Handle());
1027        cp_patches->at_put(i, patch);
1028      }
1029    }
1030  }
1031
1032  ClassFileStream st(class_bytes, class_bytes_length, (char*) host_source);
1033
1034  instanceKlassHandle anon_klass;
1035  {
1036    Symbol* no_class_name = NULL;
1037    Klass* anonk = SystemDictionary::parse_stream(no_class_name,
1038                                                    host_loader, host_domain,
1039                                                    &st, host_klass, cp_patches,
1040                                                    CHECK_NULL);
1041    if (anonk == NULL)  return NULL;
1042    anon_klass = instanceKlassHandle(THREAD, anonk);
1043  }
1044
1045  return anon_klass;
1046}
1047
1048UNSAFE_ENTRY(jclass, Unsafe_DefineAnonymousClass(JNIEnv *env, jobject unsafe, jclass host_class, jbyteArray data, jobjectArray cp_patches_jh))
1049{
1050  instanceKlassHandle anon_klass;
1051  jobject res_jh = NULL;
1052
1053  UnsafeWrapper("Unsafe_DefineAnonymousClass");
1054  ResourceMark rm(THREAD);
1055
1056  HeapWord* temp_alloc = NULL;
1057
1058  anon_klass = Unsafe_DefineAnonymousClass_impl(env, host_class, data,
1059                                                cp_patches_jh,
1060                                                   &temp_alloc, THREAD);
1061  if (anon_klass() != NULL)
1062    res_jh = JNIHandles::make_local(env, anon_klass->java_mirror());
1063
1064  // try/finally clause:
1065  if (temp_alloc != NULL) {
1066    FREE_C_HEAP_ARRAY(HeapWord, temp_alloc, mtInternal);
1067  }
1068
1069  // The anonymous class loader data has been artificially been kept alive to
1070  // this point.   The mirror and any instances of this class have to keep
1071  // it alive afterwards.
1072  if (anon_klass() != NULL) {
1073    anon_klass->class_loader_data()->set_keep_alive(false);
1074  }
1075
1076  // let caller initialize it as needed...
1077
1078  return (jclass) res_jh;
1079}
1080UNSAFE_END
1081
1082
1083
1084UNSAFE_ENTRY(void, Unsafe_MonitorEnter(JNIEnv *env, jobject unsafe, jobject jobj))
1085  UnsafeWrapper("Unsafe_MonitorEnter");
1086  {
1087    if (jobj == NULL) {
1088      THROW(vmSymbols::java_lang_NullPointerException());
1089    }
1090    Handle obj(thread, JNIHandles::resolve_non_null(jobj));
1091    ObjectSynchronizer::jni_enter(obj, CHECK);
1092  }
1093UNSAFE_END
1094
1095
1096UNSAFE_ENTRY(jboolean, Unsafe_TryMonitorEnter(JNIEnv *env, jobject unsafe, jobject jobj))
1097  UnsafeWrapper("Unsafe_TryMonitorEnter");
1098  {
1099    if (jobj == NULL) {
1100      THROW_(vmSymbols::java_lang_NullPointerException(), JNI_FALSE);
1101    }
1102    Handle obj(thread, JNIHandles::resolve_non_null(jobj));
1103    bool res = ObjectSynchronizer::jni_try_enter(obj, CHECK_0);
1104    return (res ? JNI_TRUE : JNI_FALSE);
1105  }
1106UNSAFE_END
1107
1108
1109UNSAFE_ENTRY(void, Unsafe_MonitorExit(JNIEnv *env, jobject unsafe, jobject jobj))
1110  UnsafeWrapper("Unsafe_MonitorExit");
1111  {
1112    if (jobj == NULL) {
1113      THROW(vmSymbols::java_lang_NullPointerException());
1114    }
1115    Handle obj(THREAD, JNIHandles::resolve_non_null(jobj));
1116    ObjectSynchronizer::jni_exit(obj(), CHECK);
1117  }
1118UNSAFE_END
1119
1120
1121UNSAFE_ENTRY(void, Unsafe_ThrowException(JNIEnv *env, jobject unsafe, jthrowable thr))
1122  UnsafeWrapper("Unsafe_ThrowException");
1123  {
1124    ThreadToNativeFromVM ttnfv(thread);
1125    env->Throw(thr);
1126  }
1127UNSAFE_END
1128
1129// JSR166 ------------------------------------------------------------------
1130
1131UNSAFE_ENTRY(jboolean, Unsafe_CompareAndSwapObject(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jobject e_h, jobject x_h))
1132  UnsafeWrapper("Unsafe_CompareAndSwapObject");
1133  oop x = JNIHandles::resolve(x_h);
1134  oop e = JNIHandles::resolve(e_h);
1135  oop p = JNIHandles::resolve(obj);
1136  HeapWord* addr = (HeapWord *)index_oop_from_field_offset_long(p, offset);
1137  oop res = oopDesc::atomic_compare_exchange_oop(x, addr, e, true);
1138  jboolean success  = (res == e);
1139  if (success)
1140    update_barrier_set((void*)addr, x);
1141  return success;
1142UNSAFE_END
1143
1144UNSAFE_ENTRY(jboolean, Unsafe_CompareAndSwapInt(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jint e, jint x))
1145  UnsafeWrapper("Unsafe_CompareAndSwapInt");
1146  oop p = JNIHandles::resolve(obj);
1147  jint* addr = (jint *) index_oop_from_field_offset_long(p, offset);
1148  return (jint)(Atomic::cmpxchg(x, addr, e)) == e;
1149UNSAFE_END
1150
1151UNSAFE_ENTRY(jboolean, Unsafe_CompareAndSwapLong(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jlong e, jlong x))
1152  UnsafeWrapper("Unsafe_CompareAndSwapLong");
1153  Handle p (THREAD, JNIHandles::resolve(obj));
1154  jlong* addr = (jlong*)(index_oop_from_field_offset_long(p(), offset));
1155  if (VM_Version::supports_cx8())
1156    return (jlong)(Atomic::cmpxchg(x, addr, e)) == e;
1157  else {
1158    jboolean success = false;
1159    ObjectLocker ol(p, THREAD);
1160    if (*addr == e) { *addr = x; success = true; }
1161    return success;
1162  }
1163UNSAFE_END
1164
1165UNSAFE_ENTRY(void, Unsafe_Park(JNIEnv *env, jobject unsafe, jboolean isAbsolute, jlong time))
1166  UnsafeWrapper("Unsafe_Park");
1167  EventThreadPark event;
1168  HOTSPOT_THREAD_PARK_BEGIN((uintptr_t) thread->parker(), (int) isAbsolute, time);
1169
1170  JavaThreadParkedState jtps(thread, time != 0);
1171  thread->parker()->park(isAbsolute != 0, time);
1172
1173  HOTSPOT_THREAD_PARK_END((uintptr_t) thread->parker());
1174  if (event.should_commit()) {
1175    oop obj = thread->current_park_blocker();
1176    event.set_klass((obj != NULL) ? obj->klass() : NULL);
1177    event.set_timeout(time);
1178    event.set_address((obj != NULL) ? (TYPE_ADDRESS) cast_from_oop<uintptr_t>(obj) : 0);
1179    event.commit();
1180  }
1181UNSAFE_END
1182
1183UNSAFE_ENTRY(void, Unsafe_Unpark(JNIEnv *env, jobject unsafe, jobject jthread))
1184  UnsafeWrapper("Unsafe_Unpark");
1185  Parker* p = NULL;
1186  if (jthread != NULL) {
1187    oop java_thread = JNIHandles::resolve_non_null(jthread);
1188    if (java_thread != NULL) {
1189      jlong lp = java_lang_Thread::park_event(java_thread);
1190      if (lp != 0) {
1191        // This cast is OK even though the jlong might have been read
1192        // non-atomically on 32bit systems, since there, one word will
1193        // always be zero anyway and the value set is always the same
1194        p = (Parker*)addr_from_java(lp);
1195      } else {
1196        // Grab lock if apparently null or using older version of library
1197        MutexLocker mu(Threads_lock);
1198        java_thread = JNIHandles::resolve_non_null(jthread);
1199        if (java_thread != NULL) {
1200          JavaThread* thr = java_lang_Thread::thread(java_thread);
1201          if (thr != NULL) {
1202            p = thr->parker();
1203            if (p != NULL) { // Bind to Java thread for next time.
1204              java_lang_Thread::set_park_event(java_thread, addr_to_java(p));
1205            }
1206          }
1207        }
1208      }
1209    }
1210  }
1211  if (p != NULL) {
1212    HOTSPOT_THREAD_UNPARK((uintptr_t) p);
1213    p->unpark();
1214  }
1215UNSAFE_END
1216
1217UNSAFE_ENTRY(jint, Unsafe_Loadavg(JNIEnv *env, jobject unsafe, jdoubleArray loadavg, jint nelem))
1218  UnsafeWrapper("Unsafe_Loadavg");
1219  const int max_nelem = 3;
1220  double la[max_nelem];
1221  jint ret;
1222
1223  typeArrayOop a = typeArrayOop(JNIHandles::resolve_non_null(loadavg));
1224  assert(a->is_typeArray(), "must be type array");
1225
1226  if (nelem < 0 || nelem > max_nelem || a->length() < nelem) {
1227    ThreadToNativeFromVM ttnfv(thread);
1228    throw_new(env, "ArrayIndexOutOfBoundsException");
1229    return -1;
1230  }
1231
1232  ret = os::loadavg(la, nelem);
1233  if (ret == -1) return -1;
1234
1235  // if successful, ret is the number of samples actually retrieved.
1236  assert(ret >= 0 && ret <= max_nelem, "Unexpected loadavg return value");
1237  switch(ret) {
1238    case 3: a->double_at_put(2, (jdouble)la[2]); // fall through
1239    case 2: a->double_at_put(1, (jdouble)la[1]); // fall through
1240    case 1: a->double_at_put(0, (jdouble)la[0]); break;
1241  }
1242  return ret;
1243UNSAFE_END
1244
1245UNSAFE_ENTRY(void, Unsafe_PrefetchRead(JNIEnv* env, jclass ignored, jobject obj, jlong offset))
1246  UnsafeWrapper("Unsafe_PrefetchRead");
1247  oop p = JNIHandles::resolve(obj);
1248  void* addr = index_oop_from_field_offset_long(p, 0);
1249  Prefetch::read(addr, (intx)offset);
1250UNSAFE_END
1251
1252UNSAFE_ENTRY(void, Unsafe_PrefetchWrite(JNIEnv* env, jclass ignored, jobject obj, jlong offset))
1253  UnsafeWrapper("Unsafe_PrefetchWrite");
1254  oop p = JNIHandles::resolve(obj);
1255  void* addr = index_oop_from_field_offset_long(p, 0);
1256  Prefetch::write(addr, (intx)offset);
1257UNSAFE_END
1258
1259
1260/// JVM_RegisterUnsafeMethods
1261
1262#define ADR "J"
1263
1264#define LANG "Ljava/lang/"
1265
1266#define OBJ LANG"Object;"
1267#define CLS LANG"Class;"
1268#define CTR LANG"reflect/Constructor;"
1269#define FLD LANG"reflect/Field;"
1270#define MTH LANG"reflect/Method;"
1271#define THR LANG"Throwable;"
1272
1273#define DC0_Args LANG"String;[BII"
1274#define DC_Args  DC0_Args LANG"ClassLoader;" "Ljava/security/ProtectionDomain;"
1275
1276#define CC (char*)  /*cast a literal from (const char*)*/
1277#define FN_PTR(f) CAST_FROM_FN_PTR(void*, &f)
1278
1279// define deprecated accessors for compabitility with 1.4.0
1280#define DECLARE_GETSETOOP_140(Boolean, Z) \
1281    {CC"get"#Boolean,      CC"("OBJ"I)"#Z,      FN_PTR(Unsafe_Get##Boolean##140)}, \
1282    {CC"put"#Boolean,      CC"("OBJ"I"#Z")V",   FN_PTR(Unsafe_Set##Boolean##140)}
1283
1284// Note:  In 1.4.1, getObject and kin take both int and long offsets.
1285#define DECLARE_GETSETOOP_141(Boolean, Z) \
1286    {CC"get"#Boolean,      CC"("OBJ"J)"#Z,      FN_PTR(Unsafe_Get##Boolean)}, \
1287    {CC"put"#Boolean,      CC"("OBJ"J"#Z")V",   FN_PTR(Unsafe_Set##Boolean)}
1288
1289// Note:  In 1.5.0, there are volatile versions too
1290#define DECLARE_GETSETOOP(Boolean, Z) \
1291    {CC"get"#Boolean,      CC"("OBJ"J)"#Z,      FN_PTR(Unsafe_Get##Boolean)}, \
1292    {CC"put"#Boolean,      CC"("OBJ"J"#Z")V",   FN_PTR(Unsafe_Set##Boolean)}, \
1293    {CC"get"#Boolean"Volatile",      CC"("OBJ"J)"#Z,      FN_PTR(Unsafe_Get##Boolean##Volatile)}, \
1294    {CC"put"#Boolean"Volatile",      CC"("OBJ"J"#Z")V",   FN_PTR(Unsafe_Set##Boolean##Volatile)}
1295
1296
1297#define DECLARE_GETSETNATIVE(Byte, B) \
1298    {CC"get"#Byte,         CC"("ADR")"#B,       FN_PTR(Unsafe_GetNative##Byte)}, \
1299    {CC"put"#Byte,         CC"("ADR#B")V",      FN_PTR(Unsafe_SetNative##Byte)}
1300
1301
1302
1303// These are the methods for 1.4.0
1304static JNINativeMethod methods_140[] = {
1305    DECLARE_GETSETOOP_140(Boolean, Z),
1306    DECLARE_GETSETOOP_140(Byte, B),
1307    DECLARE_GETSETOOP_140(Short, S),
1308    DECLARE_GETSETOOP_140(Char, C),
1309    DECLARE_GETSETOOP_140(Int, I),
1310    DECLARE_GETSETOOP_140(Long, J),
1311    DECLARE_GETSETOOP_140(Float, F),
1312    DECLARE_GETSETOOP_140(Double, D),
1313
1314    DECLARE_GETSETNATIVE(Byte, B),
1315    DECLARE_GETSETNATIVE(Short, S),
1316    DECLARE_GETSETNATIVE(Char, C),
1317    DECLARE_GETSETNATIVE(Int, I),
1318    DECLARE_GETSETNATIVE(Long, J),
1319    DECLARE_GETSETNATIVE(Float, F),
1320    DECLARE_GETSETNATIVE(Double, D),
1321
1322    {CC"getAddress",         CC"("ADR")"ADR,             FN_PTR(Unsafe_GetNativeAddress)},
1323    {CC"putAddress",         CC"("ADR""ADR")V",          FN_PTR(Unsafe_SetNativeAddress)},
1324
1325    {CC"allocateMemory",     CC"(J)"ADR,                 FN_PTR(Unsafe_AllocateMemory)},
1326    {CC"reallocateMemory",   CC"("ADR"J)"ADR,            FN_PTR(Unsafe_ReallocateMemory)},
1327    {CC"freeMemory",         CC"("ADR")V",               FN_PTR(Unsafe_FreeMemory)},
1328
1329    {CC"fieldOffset",        CC"("FLD")I",               FN_PTR(Unsafe_FieldOffset)},
1330    {CC"staticFieldBase",    CC"("CLS")"OBJ,             FN_PTR(Unsafe_StaticFieldBaseFromClass)},
1331    {CC"ensureClassInitialized",CC"("CLS")V",            FN_PTR(Unsafe_EnsureClassInitialized)},
1332    {CC"arrayBaseOffset",    CC"("CLS")I",               FN_PTR(Unsafe_ArrayBaseOffset)},
1333    {CC"arrayIndexScale",    CC"("CLS")I",               FN_PTR(Unsafe_ArrayIndexScale)},
1334    {CC"addressSize",        CC"()I",                    FN_PTR(Unsafe_AddressSize)},
1335    {CC"pageSize",           CC"()I",                    FN_PTR(Unsafe_PageSize)},
1336
1337    {CC"defineClass",        CC"("DC0_Args")"CLS,        FN_PTR(Unsafe_DefineClass0)},
1338    {CC"defineClass",        CC"("DC_Args")"CLS,         FN_PTR(Unsafe_DefineClass)},
1339    {CC"allocateInstance",   CC"("CLS")"OBJ,             FN_PTR(Unsafe_AllocateInstance)},
1340    {CC"monitorEnter",       CC"("OBJ")V",               FN_PTR(Unsafe_MonitorEnter)},
1341    {CC"monitorExit",        CC"("OBJ")V",               FN_PTR(Unsafe_MonitorExit)},
1342    {CC"throwException",     CC"("THR")V",               FN_PTR(Unsafe_ThrowException)}
1343};
1344
1345// These are the methods prior to the JSR 166 changes in 1.5.0
1346static JNINativeMethod methods_141[] = {
1347    {CC"getObject",        CC"("OBJ"J)"OBJ"",   FN_PTR(Unsafe_GetObject)},
1348    {CC"putObject",        CC"("OBJ"J"OBJ")V",  FN_PTR(Unsafe_SetObject)},
1349
1350    DECLARE_GETSETOOP_141(Boolean, Z),
1351    DECLARE_GETSETOOP_141(Byte, B),
1352    DECLARE_GETSETOOP_141(Short, S),
1353    DECLARE_GETSETOOP_141(Char, C),
1354    DECLARE_GETSETOOP_141(Int, I),
1355    DECLARE_GETSETOOP_141(Long, J),
1356    DECLARE_GETSETOOP_141(Float, F),
1357    DECLARE_GETSETOOP_141(Double, D),
1358
1359    DECLARE_GETSETNATIVE(Byte, B),
1360    DECLARE_GETSETNATIVE(Short, S),
1361    DECLARE_GETSETNATIVE(Char, C),
1362    DECLARE_GETSETNATIVE(Int, I),
1363    DECLARE_GETSETNATIVE(Long, J),
1364    DECLARE_GETSETNATIVE(Float, F),
1365    DECLARE_GETSETNATIVE(Double, D),
1366
1367    {CC"getAddress",         CC"("ADR")"ADR,             FN_PTR(Unsafe_GetNativeAddress)},
1368    {CC"putAddress",         CC"("ADR""ADR")V",          FN_PTR(Unsafe_SetNativeAddress)},
1369
1370    {CC"allocateMemory",     CC"(J)"ADR,                 FN_PTR(Unsafe_AllocateMemory)},
1371    {CC"reallocateMemory",   CC"("ADR"J)"ADR,            FN_PTR(Unsafe_ReallocateMemory)},
1372    {CC"freeMemory",         CC"("ADR")V",               FN_PTR(Unsafe_FreeMemory)},
1373
1374    {CC"objectFieldOffset",  CC"("FLD")J",               FN_PTR(Unsafe_ObjectFieldOffset)},
1375    {CC"staticFieldOffset",  CC"("FLD")J",               FN_PTR(Unsafe_StaticFieldOffset)},
1376    {CC"staticFieldBase",    CC"("FLD")"OBJ,             FN_PTR(Unsafe_StaticFieldBaseFromField)},
1377    {CC"ensureClassInitialized",CC"("CLS")V",            FN_PTR(Unsafe_EnsureClassInitialized)},
1378    {CC"arrayBaseOffset",    CC"("CLS")I",               FN_PTR(Unsafe_ArrayBaseOffset)},
1379    {CC"arrayIndexScale",    CC"("CLS")I",               FN_PTR(Unsafe_ArrayIndexScale)},
1380    {CC"addressSize",        CC"()I",                    FN_PTR(Unsafe_AddressSize)},
1381    {CC"pageSize",           CC"()I",                    FN_PTR(Unsafe_PageSize)},
1382
1383    {CC"defineClass",        CC"("DC0_Args")"CLS,        FN_PTR(Unsafe_DefineClass0)},
1384    {CC"defineClass",        CC"("DC_Args")"CLS,         FN_PTR(Unsafe_DefineClass)},
1385    {CC"allocateInstance",   CC"("CLS")"OBJ,             FN_PTR(Unsafe_AllocateInstance)},
1386    {CC"monitorEnter",       CC"("OBJ")V",               FN_PTR(Unsafe_MonitorEnter)},
1387    {CC"monitorExit",        CC"("OBJ")V",               FN_PTR(Unsafe_MonitorExit)},
1388    {CC"throwException",     CC"("THR")V",               FN_PTR(Unsafe_ThrowException)}
1389
1390};
1391
1392// These are the methods prior to the JSR 166 changes in 1.6.0
1393static JNINativeMethod methods_15[] = {
1394    {CC"getObject",        CC"("OBJ"J)"OBJ"",   FN_PTR(Unsafe_GetObject)},
1395    {CC"putObject",        CC"("OBJ"J"OBJ")V",  FN_PTR(Unsafe_SetObject)},
1396    {CC"getObjectVolatile",CC"("OBJ"J)"OBJ"",   FN_PTR(Unsafe_GetObjectVolatile)},
1397    {CC"putObjectVolatile",CC"("OBJ"J"OBJ")V",  FN_PTR(Unsafe_SetObjectVolatile)},
1398
1399
1400    DECLARE_GETSETOOP(Boolean, Z),
1401    DECLARE_GETSETOOP(Byte, B),
1402    DECLARE_GETSETOOP(Short, S),
1403    DECLARE_GETSETOOP(Char, C),
1404    DECLARE_GETSETOOP(Int, I),
1405    DECLARE_GETSETOOP(Long, J),
1406    DECLARE_GETSETOOP(Float, F),
1407    DECLARE_GETSETOOP(Double, D),
1408
1409    DECLARE_GETSETNATIVE(Byte, B),
1410    DECLARE_GETSETNATIVE(Short, S),
1411    DECLARE_GETSETNATIVE(Char, C),
1412    DECLARE_GETSETNATIVE(Int, I),
1413    DECLARE_GETSETNATIVE(Long, J),
1414    DECLARE_GETSETNATIVE(Float, F),
1415    DECLARE_GETSETNATIVE(Double, D),
1416
1417    {CC"getAddress",         CC"("ADR")"ADR,             FN_PTR(Unsafe_GetNativeAddress)},
1418    {CC"putAddress",         CC"("ADR""ADR")V",          FN_PTR(Unsafe_SetNativeAddress)},
1419
1420    {CC"allocateMemory",     CC"(J)"ADR,                 FN_PTR(Unsafe_AllocateMemory)},
1421    {CC"reallocateMemory",   CC"("ADR"J)"ADR,            FN_PTR(Unsafe_ReallocateMemory)},
1422    {CC"freeMemory",         CC"("ADR")V",               FN_PTR(Unsafe_FreeMemory)},
1423
1424    {CC"objectFieldOffset",  CC"("FLD")J",               FN_PTR(Unsafe_ObjectFieldOffset)},
1425    {CC"staticFieldOffset",  CC"("FLD")J",               FN_PTR(Unsafe_StaticFieldOffset)},
1426    {CC"staticFieldBase",    CC"("FLD")"OBJ,             FN_PTR(Unsafe_StaticFieldBaseFromField)},
1427    {CC"ensureClassInitialized",CC"("CLS")V",            FN_PTR(Unsafe_EnsureClassInitialized)},
1428    {CC"arrayBaseOffset",    CC"("CLS")I",               FN_PTR(Unsafe_ArrayBaseOffset)},
1429    {CC"arrayIndexScale",    CC"("CLS")I",               FN_PTR(Unsafe_ArrayIndexScale)},
1430    {CC"addressSize",        CC"()I",                    FN_PTR(Unsafe_AddressSize)},
1431    {CC"pageSize",           CC"()I",                    FN_PTR(Unsafe_PageSize)},
1432
1433    {CC"defineClass",        CC"("DC0_Args")"CLS,        FN_PTR(Unsafe_DefineClass0)},
1434    {CC"defineClass",        CC"("DC_Args")"CLS,         FN_PTR(Unsafe_DefineClass)},
1435    {CC"allocateInstance",   CC"("CLS")"OBJ,             FN_PTR(Unsafe_AllocateInstance)},
1436    {CC"monitorEnter",       CC"("OBJ")V",               FN_PTR(Unsafe_MonitorEnter)},
1437    {CC"monitorExit",        CC"("OBJ")V",               FN_PTR(Unsafe_MonitorExit)},
1438    {CC"throwException",     CC"("THR")V",               FN_PTR(Unsafe_ThrowException)},
1439    {CC"compareAndSwapObject", CC"("OBJ"J"OBJ""OBJ")Z",  FN_PTR(Unsafe_CompareAndSwapObject)},
1440    {CC"compareAndSwapInt",  CC"("OBJ"J""I""I"")Z",      FN_PTR(Unsafe_CompareAndSwapInt)},
1441    {CC"compareAndSwapLong", CC"("OBJ"J""J""J"")Z",      FN_PTR(Unsafe_CompareAndSwapLong)},
1442    {CC"park",               CC"(ZJ)V",                  FN_PTR(Unsafe_Park)},
1443    {CC"unpark",             CC"("OBJ")V",               FN_PTR(Unsafe_Unpark)}
1444
1445};
1446
1447// These are the methods for 1.6.0 and 1.7.0
1448static JNINativeMethod methods_16[] = {
1449    {CC"getObject",        CC"("OBJ"J)"OBJ"",   FN_PTR(Unsafe_GetObject)},
1450    {CC"putObject",        CC"("OBJ"J"OBJ")V",  FN_PTR(Unsafe_SetObject)},
1451    {CC"getObjectVolatile",CC"("OBJ"J)"OBJ"",   FN_PTR(Unsafe_GetObjectVolatile)},
1452    {CC"putObjectVolatile",CC"("OBJ"J"OBJ")V",  FN_PTR(Unsafe_SetObjectVolatile)},
1453
1454    DECLARE_GETSETOOP(Boolean, Z),
1455    DECLARE_GETSETOOP(Byte, B),
1456    DECLARE_GETSETOOP(Short, S),
1457    DECLARE_GETSETOOP(Char, C),
1458    DECLARE_GETSETOOP(Int, I),
1459    DECLARE_GETSETOOP(Long, J),
1460    DECLARE_GETSETOOP(Float, F),
1461    DECLARE_GETSETOOP(Double, D),
1462
1463    DECLARE_GETSETNATIVE(Byte, B),
1464    DECLARE_GETSETNATIVE(Short, S),
1465    DECLARE_GETSETNATIVE(Char, C),
1466    DECLARE_GETSETNATIVE(Int, I),
1467    DECLARE_GETSETNATIVE(Long, J),
1468    DECLARE_GETSETNATIVE(Float, F),
1469    DECLARE_GETSETNATIVE(Double, D),
1470
1471    {CC"getAddress",         CC"("ADR")"ADR,             FN_PTR(Unsafe_GetNativeAddress)},
1472    {CC"putAddress",         CC"("ADR""ADR")V",          FN_PTR(Unsafe_SetNativeAddress)},
1473
1474    {CC"allocateMemory",     CC"(J)"ADR,                 FN_PTR(Unsafe_AllocateMemory)},
1475    {CC"reallocateMemory",   CC"("ADR"J)"ADR,            FN_PTR(Unsafe_ReallocateMemory)},
1476    {CC"freeMemory",         CC"("ADR")V",               FN_PTR(Unsafe_FreeMemory)},
1477
1478    {CC"objectFieldOffset",  CC"("FLD")J",               FN_PTR(Unsafe_ObjectFieldOffset)},
1479    {CC"staticFieldOffset",  CC"("FLD")J",               FN_PTR(Unsafe_StaticFieldOffset)},
1480    {CC"staticFieldBase",    CC"("FLD")"OBJ,             FN_PTR(Unsafe_StaticFieldBaseFromField)},
1481    {CC"ensureClassInitialized",CC"("CLS")V",            FN_PTR(Unsafe_EnsureClassInitialized)},
1482    {CC"arrayBaseOffset",    CC"("CLS")I",               FN_PTR(Unsafe_ArrayBaseOffset)},
1483    {CC"arrayIndexScale",    CC"("CLS")I",               FN_PTR(Unsafe_ArrayIndexScale)},
1484    {CC"addressSize",        CC"()I",                    FN_PTR(Unsafe_AddressSize)},
1485    {CC"pageSize",           CC"()I",                    FN_PTR(Unsafe_PageSize)},
1486
1487    {CC"defineClass",        CC"("DC0_Args")"CLS,        FN_PTR(Unsafe_DefineClass0)},
1488    {CC"defineClass",        CC"("DC_Args")"CLS,         FN_PTR(Unsafe_DefineClass)},
1489    {CC"allocateInstance",   CC"("CLS")"OBJ,             FN_PTR(Unsafe_AllocateInstance)},
1490    {CC"monitorEnter",       CC"("OBJ")V",               FN_PTR(Unsafe_MonitorEnter)},
1491    {CC"monitorExit",        CC"("OBJ")V",               FN_PTR(Unsafe_MonitorExit)},
1492    {CC"tryMonitorEnter",    CC"("OBJ")Z",               FN_PTR(Unsafe_TryMonitorEnter)},
1493    {CC"throwException",     CC"("THR")V",               FN_PTR(Unsafe_ThrowException)},
1494    {CC"compareAndSwapObject", CC"("OBJ"J"OBJ""OBJ")Z",  FN_PTR(Unsafe_CompareAndSwapObject)},
1495    {CC"compareAndSwapInt",  CC"("OBJ"J""I""I"")Z",      FN_PTR(Unsafe_CompareAndSwapInt)},
1496    {CC"compareAndSwapLong", CC"("OBJ"J""J""J"")Z",      FN_PTR(Unsafe_CompareAndSwapLong)},
1497    {CC"putOrderedObject",   CC"("OBJ"J"OBJ")V",         FN_PTR(Unsafe_SetOrderedObject)},
1498    {CC"putOrderedInt",      CC"("OBJ"JI)V",             FN_PTR(Unsafe_SetOrderedInt)},
1499    {CC"putOrderedLong",     CC"("OBJ"JJ)V",             FN_PTR(Unsafe_SetOrderedLong)},
1500    {CC"park",               CC"(ZJ)V",                  FN_PTR(Unsafe_Park)},
1501    {CC"unpark",             CC"("OBJ")V",               FN_PTR(Unsafe_Unpark)}
1502};
1503
1504// These are the methods for 1.8.0
1505static JNINativeMethod methods_18[] = {
1506    {CC"getObject",        CC"("OBJ"J)"OBJ"",   FN_PTR(Unsafe_GetObject)},
1507    {CC"putObject",        CC"("OBJ"J"OBJ")V",  FN_PTR(Unsafe_SetObject)},
1508    {CC"getObjectVolatile",CC"("OBJ"J)"OBJ"",   FN_PTR(Unsafe_GetObjectVolatile)},
1509    {CC"putObjectVolatile",CC"("OBJ"J"OBJ")V",  FN_PTR(Unsafe_SetObjectVolatile)},
1510
1511    DECLARE_GETSETOOP(Boolean, Z),
1512    DECLARE_GETSETOOP(Byte, B),
1513    DECLARE_GETSETOOP(Short, S),
1514    DECLARE_GETSETOOP(Char, C),
1515    DECLARE_GETSETOOP(Int, I),
1516    DECLARE_GETSETOOP(Long, J),
1517    DECLARE_GETSETOOP(Float, F),
1518    DECLARE_GETSETOOP(Double, D),
1519
1520    DECLARE_GETSETNATIVE(Byte, B),
1521    DECLARE_GETSETNATIVE(Short, S),
1522    DECLARE_GETSETNATIVE(Char, C),
1523    DECLARE_GETSETNATIVE(Int, I),
1524    DECLARE_GETSETNATIVE(Long, J),
1525    DECLARE_GETSETNATIVE(Float, F),
1526    DECLARE_GETSETNATIVE(Double, D),
1527
1528    {CC"getAddress",         CC"("ADR")"ADR,             FN_PTR(Unsafe_GetNativeAddress)},
1529    {CC"putAddress",         CC"("ADR""ADR")V",          FN_PTR(Unsafe_SetNativeAddress)},
1530
1531    {CC"allocateMemory",     CC"(J)"ADR,                 FN_PTR(Unsafe_AllocateMemory)},
1532    {CC"reallocateMemory",   CC"("ADR"J)"ADR,            FN_PTR(Unsafe_ReallocateMemory)},
1533    {CC"freeMemory",         CC"("ADR")V",               FN_PTR(Unsafe_FreeMemory)},
1534
1535    {CC"objectFieldOffset",  CC"("FLD")J",               FN_PTR(Unsafe_ObjectFieldOffset)},
1536    {CC"staticFieldOffset",  CC"("FLD")J",               FN_PTR(Unsafe_StaticFieldOffset)},
1537    {CC"staticFieldBase",    CC"("FLD")"OBJ,             FN_PTR(Unsafe_StaticFieldBaseFromField)},
1538    {CC"ensureClassInitialized",CC"("CLS")V",            FN_PTR(Unsafe_EnsureClassInitialized)},
1539    {CC"arrayBaseOffset",    CC"("CLS")I",               FN_PTR(Unsafe_ArrayBaseOffset)},
1540    {CC"arrayIndexScale",    CC"("CLS")I",               FN_PTR(Unsafe_ArrayIndexScale)},
1541    {CC"addressSize",        CC"()I",                    FN_PTR(Unsafe_AddressSize)},
1542    {CC"pageSize",           CC"()I",                    FN_PTR(Unsafe_PageSize)},
1543
1544    {CC"defineClass",        CC"("DC_Args")"CLS,         FN_PTR(Unsafe_DefineClass)},
1545    {CC"allocateInstance",   CC"("CLS")"OBJ,             FN_PTR(Unsafe_AllocateInstance)},
1546    {CC"monitorEnter",       CC"("OBJ")V",               FN_PTR(Unsafe_MonitorEnter)},
1547    {CC"monitorExit",        CC"("OBJ")V",               FN_PTR(Unsafe_MonitorExit)},
1548    {CC"tryMonitorEnter",    CC"("OBJ")Z",               FN_PTR(Unsafe_TryMonitorEnter)},
1549    {CC"throwException",     CC"("THR")V",               FN_PTR(Unsafe_ThrowException)},
1550    {CC"compareAndSwapObject", CC"("OBJ"J"OBJ""OBJ")Z",  FN_PTR(Unsafe_CompareAndSwapObject)},
1551    {CC"compareAndSwapInt",  CC"("OBJ"J""I""I"")Z",      FN_PTR(Unsafe_CompareAndSwapInt)},
1552    {CC"compareAndSwapLong", CC"("OBJ"J""J""J"")Z",      FN_PTR(Unsafe_CompareAndSwapLong)},
1553    {CC"putOrderedObject",   CC"("OBJ"J"OBJ")V",         FN_PTR(Unsafe_SetOrderedObject)},
1554    {CC"putOrderedInt",      CC"("OBJ"JI)V",             FN_PTR(Unsafe_SetOrderedInt)},
1555    {CC"putOrderedLong",     CC"("OBJ"JJ)V",             FN_PTR(Unsafe_SetOrderedLong)},
1556    {CC"park",               CC"(ZJ)V",                  FN_PTR(Unsafe_Park)},
1557    {CC"unpark",             CC"("OBJ")V",               FN_PTR(Unsafe_Unpark)}
1558};
1559
1560JNINativeMethod loadavg_method[] = {
1561    {CC"getLoadAverage",     CC"([DI)I",                 FN_PTR(Unsafe_Loadavg)}
1562};
1563
1564JNINativeMethod prefetch_methods[] = {
1565    {CC"prefetchRead",       CC"("OBJ"J)V",              FN_PTR(Unsafe_PrefetchRead)},
1566    {CC"prefetchWrite",      CC"("OBJ"J)V",              FN_PTR(Unsafe_PrefetchWrite)},
1567    {CC"prefetchReadStatic", CC"("OBJ"J)V",              FN_PTR(Unsafe_PrefetchRead)},
1568    {CC"prefetchWriteStatic",CC"("OBJ"J)V",              FN_PTR(Unsafe_PrefetchWrite)}
1569};
1570
1571JNINativeMethod memcopy_methods_17[] = {
1572    {CC"copyMemory",         CC"("OBJ"J"OBJ"JJ)V",       FN_PTR(Unsafe_CopyMemory2)},
1573    {CC"setMemory",          CC"("OBJ"JJB)V",            FN_PTR(Unsafe_SetMemory2)}
1574};
1575
1576JNINativeMethod memcopy_methods_15[] = {
1577    {CC"setMemory",          CC"("ADR"JB)V",             FN_PTR(Unsafe_SetMemory)},
1578    {CC"copyMemory",         CC"("ADR ADR"J)V",          FN_PTR(Unsafe_CopyMemory)}
1579};
1580
1581JNINativeMethod anonk_methods[] = {
1582    {CC"defineAnonymousClass", CC"("DAC_Args")"CLS,      FN_PTR(Unsafe_DefineAnonymousClass)},
1583};
1584
1585JNINativeMethod lform_methods[] = {
1586    {CC"shouldBeInitialized",CC"("CLS")Z",               FN_PTR(Unsafe_ShouldBeInitialized)},
1587};
1588
1589JNINativeMethod fence_methods[] = {
1590    {CC"loadFence",          CC"()V",                    FN_PTR(Unsafe_LoadFence)},
1591    {CC"storeFence",         CC"()V",                    FN_PTR(Unsafe_StoreFence)},
1592    {CC"fullFence",          CC"()V",                    FN_PTR(Unsafe_FullFence)},
1593};
1594
1595#undef CC
1596#undef FN_PTR
1597
1598#undef ADR
1599#undef LANG
1600#undef OBJ
1601#undef CLS
1602#undef CTR
1603#undef FLD
1604#undef MTH
1605#undef THR
1606#undef DC0_Args
1607#undef DC_Args
1608
1609#undef DECLARE_GETSETOOP
1610#undef DECLARE_GETSETNATIVE
1611
1612
1613/**
1614 * Helper method to register native methods.
1615 */
1616static bool register_natives(const char* message, JNIEnv* env, jclass clazz, const JNINativeMethod* methods, jint nMethods) {
1617  int status = env->RegisterNatives(clazz, methods, nMethods);
1618  if (status < 0 || env->ExceptionOccurred()) {
1619    if (PrintMiscellaneous && (Verbose || WizardMode)) {
1620      tty->print_cr("Unsafe:  failed registering %s", message);
1621    }
1622    env->ExceptionClear();
1623    return false;
1624  } else {
1625    if (PrintMiscellaneous && (Verbose || WizardMode)) {
1626      tty->print_cr("Unsafe:  successfully registered %s", message);
1627    }
1628    return true;
1629  }
1630}
1631
1632
1633// This one function is exported, used by NativeLookup.
1634// The Unsafe_xxx functions above are called only from the interpreter.
1635// The optimizer looks at names and signatures to recognize
1636// individual functions.
1637
1638JVM_ENTRY(void, JVM_RegisterUnsafeMethods(JNIEnv *env, jclass unsafecls))
1639  UnsafeWrapper("JVM_RegisterUnsafeMethods");
1640  {
1641    ThreadToNativeFromVM ttnfv(thread);
1642
1643    // Unsafe methods
1644    {
1645      bool success = false;
1646      // We need to register the 1.6 methods first because the 1.8 methods would register fine on 1.7 and 1.6
1647      if (!success) {
1648        success = register_natives("1.6 methods",   env, unsafecls, methods_16,  sizeof(methods_16)/sizeof(JNINativeMethod));
1649      }
1650      if (!success) {
1651        success = register_natives("1.8 methods",   env, unsafecls, methods_18,  sizeof(methods_18)/sizeof(JNINativeMethod));
1652      }
1653      if (!success) {
1654        success = register_natives("1.5 methods",   env, unsafecls, methods_15,  sizeof(methods_15)/sizeof(JNINativeMethod));
1655      }
1656      if (!success) {
1657        success = register_natives("1.4.1 methods", env, unsafecls, methods_141, sizeof(methods_141)/sizeof(JNINativeMethod));
1658      }
1659      if (!success) {
1660        success = register_natives("1.4.0 methods", env, unsafecls, methods_140, sizeof(methods_140)/sizeof(JNINativeMethod));
1661      }
1662      guarantee(success, "register unsafe natives");
1663    }
1664
1665    // Unsafe.getLoadAverage
1666    register_natives("1.6 loadavg method", env, unsafecls, loadavg_method, sizeof(loadavg_method)/sizeof(JNINativeMethod));
1667
1668    // Prefetch methods
1669    register_natives("1.6 prefetch methods", env, unsafecls, prefetch_methods, sizeof(prefetch_methods)/sizeof(JNINativeMethod));
1670
1671    // Memory copy methods
1672    {
1673      bool success = false;
1674      if (!success) {
1675        success = register_natives("1.7 memory copy methods", env, unsafecls, memcopy_methods_17, sizeof(memcopy_methods_17)/sizeof(JNINativeMethod));
1676      }
1677      if (!success) {
1678        success = register_natives("1.5 memory copy methods", env, unsafecls, memcopy_methods_15, sizeof(memcopy_methods_15)/sizeof(JNINativeMethod));
1679      }
1680    }
1681
1682    // Unsafe.defineAnonymousClass
1683    register_natives("1.7 define anonymous class method", env, unsafecls, anonk_methods, sizeof(anonk_methods)/sizeof(JNINativeMethod));
1684
1685    // Unsafe.shouldBeInitialized
1686    register_natives("1.7 LambdaForm support", env, unsafecls, lform_methods, sizeof(lform_methods)/sizeof(JNINativeMethod));
1687
1688    // Fence methods
1689    register_natives("1.8 fence methods", env, unsafecls, fence_methods, sizeof(fence_methods)/sizeof(JNINativeMethod));
1690  }
1691JVM_END
1692