jvm.cpp revision 1472:c18cbe5936b8
1/*
2 * Copyright (c) 1997, 2009, 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 "incls/_precompiled.incl"
26#include "incls/_jvm.cpp.incl"
27#include <errno.h>
28
29HS_DTRACE_PROBE_DECL1(hotspot, thread__sleep__begin, long long);
30HS_DTRACE_PROBE_DECL1(hotspot, thread__sleep__end, int);
31HS_DTRACE_PROBE_DECL0(hotspot, thread__yield);
32
33/*
34  NOTE about use of any ctor or function call that can trigger a safepoint/GC:
35  such ctors and calls MUST NOT come between an oop declaration/init and its
36  usage because if objects are move this may cause various memory stomps, bus
37  errors and segfaults. Here is a cookbook for causing so called "naked oop
38  failures":
39
40      JVM_ENTRY(jobjectArray, JVM_GetClassDeclaredFields<etc> {
41          JVMWrapper("JVM_GetClassDeclaredFields");
42
43          // Object address to be held directly in mirror & not visible to GC
44          oop mirror = JNIHandles::resolve_non_null(ofClass);
45
46          // If this ctor can hit a safepoint, moving objects around, then
47          ComplexConstructor foo;
48
49          // Boom! mirror may point to JUNK instead of the intended object
50          (some dereference of mirror)
51
52          // Here's another call that may block for GC, making mirror stale
53          MutexLocker ml(some_lock);
54
55          // And here's an initializer that can result in a stale oop
56          // all in one step.
57          oop o = call_that_can_throw_exception(TRAPS);
58
59
60  The solution is to keep the oop declaration BELOW the ctor or function
61  call that might cause a GC, do another resolve to reassign the oop, or
62  consider use of a Handle instead of an oop so there is immunity from object
63  motion. But note that the "QUICK" entries below do not have a handlemark
64  and thus can only support use of handles passed in.
65*/
66
67static void trace_class_resolution_impl(klassOop to_class, TRAPS) {
68  ResourceMark rm;
69  int line_number = -1;
70  const char * source_file = NULL;
71  const char * trace = "explicit";
72  klassOop caller = NULL;
73  JavaThread* jthread = JavaThread::current();
74  if (jthread->has_last_Java_frame()) {
75    vframeStream vfst(jthread);
76
77    // scan up the stack skipping ClassLoader, AccessController and PrivilegedAction frames
78    symbolHandle access_controller = oopFactory::new_symbol_handle("java/security/AccessController", CHECK);
79    klassOop access_controller_klass = SystemDictionary::resolve_or_fail(access_controller, false, CHECK);
80    symbolHandle privileged_action = oopFactory::new_symbol_handle("java/security/PrivilegedAction", CHECK);
81    klassOop privileged_action_klass = SystemDictionary::resolve_or_fail(privileged_action, false, CHECK);
82
83    methodOop last_caller = NULL;
84
85    while (!vfst.at_end()) {
86      methodOop m = vfst.method();
87      if (!vfst.method()->method_holder()->klass_part()->is_subclass_of(SystemDictionary::ClassLoader_klass())&&
88          !vfst.method()->method_holder()->klass_part()->is_subclass_of(access_controller_klass) &&
89          !vfst.method()->method_holder()->klass_part()->is_subclass_of(privileged_action_klass)) {
90        break;
91      }
92      last_caller = m;
93      vfst.next();
94    }
95    // if this is called from Class.forName0 and that is called from Class.forName,
96    // then print the caller of Class.forName.  If this is Class.loadClass, then print
97    // that caller, otherwise keep quiet since this should be picked up elsewhere.
98    bool found_it = false;
99    if (!vfst.at_end() &&
100        instanceKlass::cast(vfst.method()->method_holder())->name() == vmSymbols::java_lang_Class() &&
101        vfst.method()->name() == vmSymbols::forName0_name()) {
102      vfst.next();
103      if (!vfst.at_end() &&
104          instanceKlass::cast(vfst.method()->method_holder())->name() == vmSymbols::java_lang_Class() &&
105          vfst.method()->name() == vmSymbols::forName_name()) {
106        vfst.next();
107        found_it = true;
108      }
109    } else if (last_caller != NULL &&
110               instanceKlass::cast(last_caller->method_holder())->name() ==
111               vmSymbols::java_lang_ClassLoader() &&
112               (last_caller->name() == vmSymbols::loadClassInternal_name() ||
113                last_caller->name() == vmSymbols::loadClass_name())) {
114      found_it = true;
115    } else if (!vfst.at_end()) {
116      if (vfst.method()->is_native()) {
117        // JNI call
118        found_it = true;
119      }
120    }
121    if (found_it && !vfst.at_end()) {
122      // found the caller
123      caller = vfst.method()->method_holder();
124      line_number = vfst.method()->line_number_from_bci(vfst.bci());
125      if (line_number == -1) {
126        // show method name if it's a native method
127        trace = vfst.method()->name_and_sig_as_C_string();
128      }
129      symbolOop s = instanceKlass::cast(caller)->source_file_name();
130      if (s != NULL) {
131        source_file = s->as_C_string();
132      }
133    }
134  }
135  if (caller != NULL) {
136    if (to_class != caller) {
137      const char * from = Klass::cast(caller)->external_name();
138      const char * to = Klass::cast(to_class)->external_name();
139      // print in a single call to reduce interleaving between threads
140      if (source_file != NULL) {
141        tty->print("RESOLVE %s %s %s:%d (%s)\n", from, to, source_file, line_number, trace);
142      } else {
143        tty->print("RESOLVE %s %s (%s)\n", from, to, trace);
144      }
145    }
146  }
147}
148
149void trace_class_resolution(klassOop to_class) {
150  EXCEPTION_MARK;
151  trace_class_resolution_impl(to_class, THREAD);
152  if (HAS_PENDING_EXCEPTION) {
153    CLEAR_PENDING_EXCEPTION;
154  }
155}
156
157// Wrapper to trace JVM functions
158
159#ifdef ASSERT
160  class JVMTraceWrapper : public StackObj {
161   public:
162    JVMTraceWrapper(const char* format, ...) {
163      if (TraceJVMCalls) {
164        va_list ap;
165        va_start(ap, format);
166        tty->print("JVM ");
167        tty->vprint_cr(format, ap);
168        va_end(ap);
169      }
170    }
171  };
172
173  Histogram* JVMHistogram;
174  volatile jint JVMHistogram_lock = 0;
175
176  class JVMHistogramElement : public HistogramElement {
177    public:
178     JVMHistogramElement(const char* name);
179  };
180
181  JVMHistogramElement::JVMHistogramElement(const char* elementName) {
182    _name = elementName;
183    uintx count = 0;
184
185    while (Atomic::cmpxchg(1, &JVMHistogram_lock, 0) != 0) {
186      while (OrderAccess::load_acquire(&JVMHistogram_lock) != 0) {
187        count +=1;
188        if ( (WarnOnStalledSpinLock > 0)
189          && (count % WarnOnStalledSpinLock == 0)) {
190          warning("JVMHistogram_lock seems to be stalled");
191        }
192      }
193     }
194
195    if(JVMHistogram == NULL)
196      JVMHistogram = new Histogram("JVM Call Counts",100);
197
198    JVMHistogram->add_element(this);
199    Atomic::dec(&JVMHistogram_lock);
200  }
201
202  #define JVMCountWrapper(arg) \
203      static JVMHistogramElement* e = new JVMHistogramElement(arg); \
204      if (e != NULL) e->increment_count();  // Due to bug in VC++, we need a NULL check here eventhough it should never happen!
205
206  #define JVMWrapper(arg1)                    JVMCountWrapper(arg1); JVMTraceWrapper(arg1)
207  #define JVMWrapper2(arg1, arg2)             JVMCountWrapper(arg1); JVMTraceWrapper(arg1, arg2)
208  #define JVMWrapper3(arg1, arg2, arg3)       JVMCountWrapper(arg1); JVMTraceWrapper(arg1, arg2, arg3)
209  #define JVMWrapper4(arg1, arg2, arg3, arg4) JVMCountWrapper(arg1); JVMTraceWrapper(arg1, arg2, arg3, arg4)
210#else
211  #define JVMWrapper(arg1)
212  #define JVMWrapper2(arg1, arg2)
213  #define JVMWrapper3(arg1, arg2, arg3)
214  #define JVMWrapper4(arg1, arg2, arg3, arg4)
215#endif
216
217
218// Interface version /////////////////////////////////////////////////////////////////////
219
220
221JVM_LEAF(jint, JVM_GetInterfaceVersion())
222  return JVM_INTERFACE_VERSION;
223JVM_END
224
225
226// java.lang.System //////////////////////////////////////////////////////////////////////
227
228
229JVM_LEAF(jlong, JVM_CurrentTimeMillis(JNIEnv *env, jclass ignored))
230  JVMWrapper("JVM_CurrentTimeMillis");
231  return os::javaTimeMillis();
232JVM_END
233
234JVM_LEAF(jlong, JVM_NanoTime(JNIEnv *env, jclass ignored))
235  JVMWrapper("JVM_NanoTime");
236  return os::javaTimeNanos();
237JVM_END
238
239
240JVM_ENTRY(void, JVM_ArrayCopy(JNIEnv *env, jclass ignored, jobject src, jint src_pos,
241                               jobject dst, jint dst_pos, jint length))
242  JVMWrapper("JVM_ArrayCopy");
243  // Check if we have null pointers
244  if (src == NULL || dst == NULL) {
245    THROW(vmSymbols::java_lang_NullPointerException());
246  }
247  arrayOop s = arrayOop(JNIHandles::resolve_non_null(src));
248  arrayOop d = arrayOop(JNIHandles::resolve_non_null(dst));
249  assert(s->is_oop(), "JVM_ArrayCopy: src not an oop");
250  assert(d->is_oop(), "JVM_ArrayCopy: dst not an oop");
251  // Do copy
252  Klass::cast(s->klass())->copy_array(s, src_pos, d, dst_pos, length, thread);
253JVM_END
254
255
256static void set_property(Handle props, const char* key, const char* value, TRAPS) {
257  JavaValue r(T_OBJECT);
258  // public synchronized Object put(Object key, Object value);
259  HandleMark hm(THREAD);
260  Handle key_str    = java_lang_String::create_from_platform_dependent_str(key, CHECK);
261  Handle value_str  = java_lang_String::create_from_platform_dependent_str((value != NULL ? value : ""), CHECK);
262  JavaCalls::call_virtual(&r,
263                          props,
264                          KlassHandle(THREAD, SystemDictionary::Properties_klass()),
265                          vmSymbolHandles::put_name(),
266                          vmSymbolHandles::object_object_object_signature(),
267                          key_str,
268                          value_str,
269                          THREAD);
270}
271
272
273#define PUTPROP(props, name, value) set_property((props), (name), (value), CHECK_(properties));
274
275
276JVM_ENTRY(jobject, JVM_InitProperties(JNIEnv *env, jobject properties))
277  JVMWrapper("JVM_InitProperties");
278  ResourceMark rm;
279
280  Handle props(THREAD, JNIHandles::resolve_non_null(properties));
281
282  // System property list includes both user set via -D option and
283  // jvm system specific properties.
284  for (SystemProperty* p = Arguments::system_properties(); p != NULL; p = p->next()) {
285    PUTPROP(props, p->key(), p->value());
286  }
287
288  // Convert the -XX:MaxDirectMemorySize= command line flag
289  // to the sun.nio.MaxDirectMemorySize property.
290  // Do this after setting user properties to prevent people
291  // from setting the value with a -D option, as requested.
292  {
293    char as_chars[256];
294    jio_snprintf(as_chars, sizeof(as_chars), INTX_FORMAT, MaxDirectMemorySize);
295    PUTPROP(props, "sun.nio.MaxDirectMemorySize", as_chars);
296  }
297
298  // JVM monitoring and management support
299  // Add the sun.management.compiler property for the compiler's name
300  {
301#undef CSIZE
302#if defined(_LP64) || defined(_WIN64)
303  #define CSIZE "64-Bit "
304#else
305  #define CSIZE
306#endif // 64bit
307
308#ifdef TIERED
309    const char* compiler_name = "HotSpot " CSIZE "Tiered Compilers";
310#else
311#if defined(COMPILER1)
312    const char* compiler_name = "HotSpot " CSIZE "Client Compiler";
313#elif defined(COMPILER2)
314    const char* compiler_name = "HotSpot " CSIZE "Server Compiler";
315#else
316    const char* compiler_name = "";
317#endif // compilers
318#endif // TIERED
319
320    if (*compiler_name != '\0' &&
321        (Arguments::mode() != Arguments::_int)) {
322      PUTPROP(props, "sun.management.compiler", compiler_name);
323    }
324  }
325
326  return properties;
327JVM_END
328
329
330// java.lang.Runtime /////////////////////////////////////////////////////////////////////////
331
332extern volatile jint vm_created;
333
334JVM_ENTRY_NO_ENV(void, JVM_Exit(jint code))
335  if (vm_created != 0 && (code == 0)) {
336    // The VM is about to exit. We call back into Java to check whether finalizers should be run
337    Universe::run_finalizers_on_exit();
338  }
339  before_exit(thread);
340  vm_exit(code);
341JVM_END
342
343
344JVM_ENTRY_NO_ENV(void, JVM_Halt(jint code))
345  before_exit(thread);
346  vm_exit(code);
347JVM_END
348
349
350JVM_LEAF(void, JVM_OnExit(void (*func)(void)))
351  register_on_exit_function(func);
352JVM_END
353
354
355JVM_ENTRY_NO_ENV(void, JVM_GC(void))
356  JVMWrapper("JVM_GC");
357  if (!DisableExplicitGC) {
358    Universe::heap()->collect(GCCause::_java_lang_system_gc);
359  }
360JVM_END
361
362
363JVM_LEAF(jlong, JVM_MaxObjectInspectionAge(void))
364  JVMWrapper("JVM_MaxObjectInspectionAge");
365  return Universe::heap()->millis_since_last_gc();
366JVM_END
367
368
369JVM_LEAF(void, JVM_TraceInstructions(jboolean on))
370  if (PrintJVMWarnings) warning("JVM_TraceInstructions not supported");
371JVM_END
372
373
374JVM_LEAF(void, JVM_TraceMethodCalls(jboolean on))
375  if (PrintJVMWarnings) warning("JVM_TraceMethodCalls not supported");
376JVM_END
377
378static inline jlong convert_size_t_to_jlong(size_t val) {
379  // In the 64-bit vm, a size_t can overflow a jlong (which is signed).
380  NOT_LP64 (return (jlong)val;)
381  LP64_ONLY(return (jlong)MIN2(val, (size_t)max_jlong);)
382}
383
384JVM_ENTRY_NO_ENV(jlong, JVM_TotalMemory(void))
385  JVMWrapper("JVM_TotalMemory");
386  size_t n = Universe::heap()->capacity();
387  return convert_size_t_to_jlong(n);
388JVM_END
389
390
391JVM_ENTRY_NO_ENV(jlong, JVM_FreeMemory(void))
392  JVMWrapper("JVM_FreeMemory");
393  CollectedHeap* ch = Universe::heap();
394  size_t n;
395  {
396     MutexLocker x(Heap_lock);
397     n = ch->capacity() - ch->used();
398  }
399  return convert_size_t_to_jlong(n);
400JVM_END
401
402
403JVM_ENTRY_NO_ENV(jlong, JVM_MaxMemory(void))
404  JVMWrapper("JVM_MaxMemory");
405  size_t n = Universe::heap()->max_capacity();
406  return convert_size_t_to_jlong(n);
407JVM_END
408
409
410JVM_ENTRY_NO_ENV(jint, JVM_ActiveProcessorCount(void))
411  JVMWrapper("JVM_ActiveProcessorCount");
412  return os::active_processor_count();
413JVM_END
414
415
416
417// java.lang.Throwable //////////////////////////////////////////////////////
418
419
420JVM_ENTRY(void, JVM_FillInStackTrace(JNIEnv *env, jobject receiver))
421  JVMWrapper("JVM_FillInStackTrace");
422  Handle exception(thread, JNIHandles::resolve_non_null(receiver));
423  java_lang_Throwable::fill_in_stack_trace(exception);
424JVM_END
425
426
427JVM_ENTRY(void, JVM_PrintStackTrace(JNIEnv *env, jobject receiver, jobject printable))
428  JVMWrapper("JVM_PrintStackTrace");
429  // Note: This is no longer used in Merlin, but we still support it for compatibility.
430  oop exception = JNIHandles::resolve_non_null(receiver);
431  oop stream    = JNIHandles::resolve_non_null(printable);
432  java_lang_Throwable::print_stack_trace(exception, stream);
433JVM_END
434
435
436JVM_ENTRY(jint, JVM_GetStackTraceDepth(JNIEnv *env, jobject throwable))
437  JVMWrapper("JVM_GetStackTraceDepth");
438  oop exception = JNIHandles::resolve(throwable);
439  return java_lang_Throwable::get_stack_trace_depth(exception, THREAD);
440JVM_END
441
442
443JVM_ENTRY(jobject, JVM_GetStackTraceElement(JNIEnv *env, jobject throwable, jint index))
444  JVMWrapper("JVM_GetStackTraceElement");
445  JvmtiVMObjectAllocEventCollector oam; // This ctor (throughout this module) may trigger a safepoint/GC
446  oop exception = JNIHandles::resolve(throwable);
447  oop element = java_lang_Throwable::get_stack_trace_element(exception, index, CHECK_NULL);
448  return JNIHandles::make_local(env, element);
449JVM_END
450
451
452// java.lang.Object ///////////////////////////////////////////////
453
454
455JVM_ENTRY(jint, JVM_IHashCode(JNIEnv* env, jobject handle))
456  JVMWrapper("JVM_IHashCode");
457  // as implemented in the classic virtual machine; return 0 if object is NULL
458  return handle == NULL ? 0 : ObjectSynchronizer::FastHashCode (THREAD, JNIHandles::resolve_non_null(handle)) ;
459JVM_END
460
461
462JVM_ENTRY(void, JVM_MonitorWait(JNIEnv* env, jobject handle, jlong ms))
463  JVMWrapper("JVM_MonitorWait");
464  Handle obj(THREAD, JNIHandles::resolve_non_null(handle));
465  assert(obj->is_instance() || obj->is_array(), "JVM_MonitorWait must apply to an object");
466  JavaThreadInObjectWaitState jtiows(thread, ms != 0);
467  if (JvmtiExport::should_post_monitor_wait()) {
468    JvmtiExport::post_monitor_wait((JavaThread *)THREAD, (oop)obj(), ms);
469  }
470  ObjectSynchronizer::wait(obj, ms, CHECK);
471JVM_END
472
473
474JVM_ENTRY(void, JVM_MonitorNotify(JNIEnv* env, jobject handle))
475  JVMWrapper("JVM_MonitorNotify");
476  Handle obj(THREAD, JNIHandles::resolve_non_null(handle));
477  assert(obj->is_instance() || obj->is_array(), "JVM_MonitorNotify must apply to an object");
478  ObjectSynchronizer::notify(obj, CHECK);
479JVM_END
480
481
482JVM_ENTRY(void, JVM_MonitorNotifyAll(JNIEnv* env, jobject handle))
483  JVMWrapper("JVM_MonitorNotifyAll");
484  Handle obj(THREAD, JNIHandles::resolve_non_null(handle));
485  assert(obj->is_instance() || obj->is_array(), "JVM_MonitorNotifyAll must apply to an object");
486  ObjectSynchronizer::notifyall(obj, CHECK);
487JVM_END
488
489
490JVM_ENTRY(jobject, JVM_Clone(JNIEnv* env, jobject handle))
491  JVMWrapper("JVM_Clone");
492  Handle obj(THREAD, JNIHandles::resolve_non_null(handle));
493  const KlassHandle klass (THREAD, obj->klass());
494  JvmtiVMObjectAllocEventCollector oam;
495
496#ifdef ASSERT
497  // Just checking that the cloneable flag is set correct
498  if (obj->is_javaArray()) {
499    guarantee(klass->is_cloneable(), "all arrays are cloneable");
500  } else {
501    guarantee(obj->is_instance(), "should be instanceOop");
502    bool cloneable = klass->is_subtype_of(SystemDictionary::Cloneable_klass());
503    guarantee(cloneable == klass->is_cloneable(), "incorrect cloneable flag");
504  }
505#endif
506
507  // Check if class of obj supports the Cloneable interface.
508  // All arrays are considered to be cloneable (See JLS 20.1.5)
509  if (!klass->is_cloneable()) {
510    ResourceMark rm(THREAD);
511    THROW_MSG_0(vmSymbols::java_lang_CloneNotSupportedException(), klass->external_name());
512  }
513
514  // Make shallow object copy
515  const int size = obj->size();
516  oop new_obj = NULL;
517  if (obj->is_javaArray()) {
518    const int length = ((arrayOop)obj())->length();
519    new_obj = CollectedHeap::array_allocate(klass, size, length, CHECK_NULL);
520  } else {
521    new_obj = CollectedHeap::obj_allocate(klass, size, CHECK_NULL);
522  }
523  // 4839641 (4840070): We must do an oop-atomic copy, because if another thread
524  // is modifying a reference field in the clonee, a non-oop-atomic copy might
525  // be suspended in the middle of copying the pointer and end up with parts
526  // of two different pointers in the field.  Subsequent dereferences will crash.
527  // 4846409: an oop-copy of objects with long or double fields or arrays of same
528  // won't copy the longs/doubles atomically in 32-bit vm's, so we copy jlongs instead
529  // of oops.  We know objects are aligned on a minimum of an jlong boundary.
530  // The same is true of StubRoutines::object_copy and the various oop_copy
531  // variants, and of the code generated by the inline_native_clone intrinsic.
532  assert(MinObjAlignmentInBytes >= BytesPerLong, "objects misaligned");
533  Copy::conjoint_jlongs_atomic((jlong*)obj(), (jlong*)new_obj,
534                               (size_t)align_object_size(size) / HeapWordsPerLong);
535  // Clear the header
536  new_obj->init_mark();
537
538  // Store check (mark entire object and let gc sort it out)
539  BarrierSet* bs = Universe::heap()->barrier_set();
540  assert(bs->has_write_region_opt(), "Barrier set does not have write_region");
541  bs->write_region(MemRegion((HeapWord*)new_obj, size));
542
543  // Caution: this involves a java upcall, so the clone should be
544  // "gc-robust" by this stage.
545  if (klass->has_finalizer()) {
546    assert(obj->is_instance(), "should be instanceOop");
547    new_obj = instanceKlass::register_finalizer(instanceOop(new_obj), CHECK_NULL);
548  }
549
550  return JNIHandles::make_local(env, oop(new_obj));
551JVM_END
552
553// java.lang.Compiler ////////////////////////////////////////////////////
554
555// The initial cuts of the HotSpot VM will not support JITs, and all existing
556// JITs would need extensive changes to work with HotSpot.  The JIT-related JVM
557// functions are all silently ignored unless JVM warnings are printed.
558
559JVM_LEAF(void, JVM_InitializeCompiler (JNIEnv *env, jclass compCls))
560  if (PrintJVMWarnings) warning("JVM_InitializeCompiler not supported");
561JVM_END
562
563
564JVM_LEAF(jboolean, JVM_IsSilentCompiler(JNIEnv *env, jclass compCls))
565  if (PrintJVMWarnings) warning("JVM_IsSilentCompiler not supported");
566  return JNI_FALSE;
567JVM_END
568
569
570JVM_LEAF(jboolean, JVM_CompileClass(JNIEnv *env, jclass compCls, jclass cls))
571  if (PrintJVMWarnings) warning("JVM_CompileClass not supported");
572  return JNI_FALSE;
573JVM_END
574
575
576JVM_LEAF(jboolean, JVM_CompileClasses(JNIEnv *env, jclass cls, jstring jname))
577  if (PrintJVMWarnings) warning("JVM_CompileClasses not supported");
578  return JNI_FALSE;
579JVM_END
580
581
582JVM_LEAF(jobject, JVM_CompilerCommand(JNIEnv *env, jclass compCls, jobject arg))
583  if (PrintJVMWarnings) warning("JVM_CompilerCommand not supported");
584  return NULL;
585JVM_END
586
587
588JVM_LEAF(void, JVM_EnableCompiler(JNIEnv *env, jclass compCls))
589  if (PrintJVMWarnings) warning("JVM_EnableCompiler not supported");
590JVM_END
591
592
593JVM_LEAF(void, JVM_DisableCompiler(JNIEnv *env, jclass compCls))
594  if (PrintJVMWarnings) warning("JVM_DisableCompiler not supported");
595JVM_END
596
597
598
599// Error message support //////////////////////////////////////////////////////
600
601JVM_LEAF(jint, JVM_GetLastErrorString(char *buf, int len))
602  JVMWrapper("JVM_GetLastErrorString");
603  return hpi::lasterror(buf, len);
604JVM_END
605
606
607// java.io.File ///////////////////////////////////////////////////////////////
608
609JVM_LEAF(char*, JVM_NativePath(char* path))
610  JVMWrapper2("JVM_NativePath (%s)", path);
611  return hpi::native_path(path);
612JVM_END
613
614
615// Misc. class handling ///////////////////////////////////////////////////////////
616
617
618JVM_ENTRY(jclass, JVM_GetCallerClass(JNIEnv* env, int depth))
619  JVMWrapper("JVM_GetCallerClass");
620  klassOop k = thread->security_get_caller_class(depth);
621  return (k == NULL) ? NULL : (jclass) JNIHandles::make_local(env, Klass::cast(k)->java_mirror());
622JVM_END
623
624
625JVM_ENTRY(jclass, JVM_FindPrimitiveClass(JNIEnv* env, const char* utf))
626  JVMWrapper("JVM_FindPrimitiveClass");
627  oop mirror = NULL;
628  BasicType t = name2type(utf);
629  if (t != T_ILLEGAL && t != T_OBJECT && t != T_ARRAY) {
630    mirror = Universe::java_mirror(t);
631  }
632  if (mirror == NULL) {
633    THROW_MSG_0(vmSymbols::java_lang_ClassNotFoundException(), (char*) utf);
634  } else {
635    return (jclass) JNIHandles::make_local(env, mirror);
636  }
637JVM_END
638
639
640JVM_ENTRY(void, JVM_ResolveClass(JNIEnv* env, jclass cls))
641  JVMWrapper("JVM_ResolveClass");
642  if (PrintJVMWarnings) warning("JVM_ResolveClass not implemented");
643JVM_END
644
645
646// Returns a class loaded by the bootstrap class loader; or null
647// if not found.  ClassNotFoundException is not thrown.
648//
649// Rationale behind JVM_FindClassFromBootLoader
650// a> JVM_FindClassFromClassLoader was never exported in the export tables.
651// b> because of (a) java.dll has a direct dependecy on the  unexported
652//    private symbol "_JVM_FindClassFromClassLoader@20".
653// c> the launcher cannot use the private symbol as it dynamically opens
654//    the entry point, so if something changes, the launcher will fail
655//    unexpectedly at runtime, it is safest for the launcher to dlopen a
656//    stable exported interface.
657// d> re-exporting JVM_FindClassFromClassLoader as public, will cause its
658//    signature to change from _JVM_FindClassFromClassLoader@20 to
659//    JVM_FindClassFromClassLoader and will not be backward compatible
660//    with older JDKs.
661// Thus a public/stable exported entry point is the right solution,
662// public here means public in linker semantics, and is exported only
663// to the JDK, and is not intended to be a public API.
664
665JVM_ENTRY(jclass, JVM_FindClassFromBootLoader(JNIEnv* env,
666                                              const char* name))
667  JVMWrapper2("JVM_FindClassFromBootLoader %s", name);
668
669  // Java libraries should ensure that name is never null...
670  if (name == NULL || (int)strlen(name) > symbolOopDesc::max_length()) {
671    // It's impossible to create this class;  the name cannot fit
672    // into the constant pool.
673    return NULL;
674  }
675
676  symbolHandle h_name = oopFactory::new_symbol_handle(name, CHECK_NULL);
677  klassOop k = SystemDictionary::resolve_or_null(h_name, CHECK_NULL);
678  if (k == NULL) {
679    return NULL;
680  }
681
682  if (TraceClassResolution) {
683    trace_class_resolution(k);
684  }
685  return (jclass) JNIHandles::make_local(env, Klass::cast(k)->java_mirror());
686JVM_END
687
688JVM_ENTRY(jclass, JVM_FindClassFromClassLoader(JNIEnv* env, const char* name,
689                                               jboolean init, jobject loader,
690                                               jboolean throwError))
691  JVMWrapper3("JVM_FindClassFromClassLoader %s throw %s", name,
692               throwError ? "error" : "exception");
693  // Java libraries should ensure that name is never null...
694  if (name == NULL || (int)strlen(name) > symbolOopDesc::max_length()) {
695    // It's impossible to create this class;  the name cannot fit
696    // into the constant pool.
697    if (throwError) {
698      THROW_MSG_0(vmSymbols::java_lang_NoClassDefFoundError(), name);
699    } else {
700      THROW_MSG_0(vmSymbols::java_lang_ClassNotFoundException(), name);
701    }
702  }
703  symbolHandle h_name = oopFactory::new_symbol_handle(name, CHECK_NULL);
704  Handle h_loader(THREAD, JNIHandles::resolve(loader));
705  jclass result = find_class_from_class_loader(env, h_name, init, h_loader,
706                                               Handle(), throwError, THREAD);
707
708  if (TraceClassResolution && result != NULL) {
709    trace_class_resolution(java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(result)));
710  }
711  return result;
712JVM_END
713
714
715JVM_ENTRY(jclass, JVM_FindClassFromClass(JNIEnv *env, const char *name,
716                                         jboolean init, jclass from))
717  JVMWrapper2("JVM_FindClassFromClass %s", name);
718  if (name == NULL || (int)strlen(name) > symbolOopDesc::max_length()) {
719    // It's impossible to create this class;  the name cannot fit
720    // into the constant pool.
721    THROW_MSG_0(vmSymbols::java_lang_NoClassDefFoundError(), name);
722  }
723  symbolHandle h_name = oopFactory::new_symbol_handle(name, CHECK_NULL);
724  oop from_class_oop = JNIHandles::resolve(from);
725  klassOop from_class = (from_class_oop == NULL)
726                           ? (klassOop)NULL
727                           : java_lang_Class::as_klassOop(from_class_oop);
728  oop class_loader = NULL;
729  oop protection_domain = NULL;
730  if (from_class != NULL) {
731    class_loader = Klass::cast(from_class)->class_loader();
732    protection_domain = Klass::cast(from_class)->protection_domain();
733  }
734  Handle h_loader(THREAD, class_loader);
735  Handle h_prot  (THREAD, protection_domain);
736  jclass result = find_class_from_class_loader(env, h_name, init, h_loader,
737                                               h_prot, true, thread);
738
739  if (TraceClassResolution && result != NULL) {
740    // this function is generally only used for class loading during verification.
741    ResourceMark rm;
742    oop from_mirror = JNIHandles::resolve_non_null(from);
743    klassOop from_class = java_lang_Class::as_klassOop(from_mirror);
744    const char * from_name = Klass::cast(from_class)->external_name();
745
746    oop mirror = JNIHandles::resolve_non_null(result);
747    klassOop to_class = java_lang_Class::as_klassOop(mirror);
748    const char * to = Klass::cast(to_class)->external_name();
749    tty->print("RESOLVE %s %s (verification)\n", from_name, to);
750  }
751
752  return result;
753JVM_END
754
755static void is_lock_held_by_thread(Handle loader, PerfCounter* counter, TRAPS) {
756  if (loader.is_null()) {
757    return;
758  }
759
760  // check whether the current caller thread holds the lock or not.
761  // If not, increment the corresponding counter
762  if (ObjectSynchronizer::query_lock_ownership((JavaThread*)THREAD, loader) !=
763      ObjectSynchronizer::owner_self) {
764    counter->inc();
765  }
766}
767
768// common code for JVM_DefineClass() and JVM_DefineClassWithSource()
769// and JVM_DefineClassWithSourceCond()
770static jclass jvm_define_class_common(JNIEnv *env, const char *name,
771                                      jobject loader, const jbyte *buf,
772                                      jsize len, jobject pd, const char *source,
773                                      jboolean verify, TRAPS) {
774  if (source == NULL)  source = "__JVM_DefineClass__";
775
776  assert(THREAD->is_Java_thread(), "must be a JavaThread");
777  JavaThread* jt = (JavaThread*) THREAD;
778
779  PerfClassTraceTime vmtimer(ClassLoader::perf_define_appclass_time(),
780                             ClassLoader::perf_define_appclass_selftime(),
781                             ClassLoader::perf_define_appclasses(),
782                             jt->get_thread_stat()->perf_recursion_counts_addr(),
783                             jt->get_thread_stat()->perf_timers_addr(),
784                             PerfClassTraceTime::DEFINE_CLASS);
785
786  if (UsePerfData) {
787    ClassLoader::perf_app_classfile_bytes_read()->inc(len);
788  }
789
790  // Since exceptions can be thrown, class initialization can take place
791  // if name is NULL no check for class name in .class stream has to be made.
792  symbolHandle class_name;
793  if (name != NULL) {
794    const int str_len = (int)strlen(name);
795    if (str_len > symbolOopDesc::max_length()) {
796      // It's impossible to create this class;  the name cannot fit
797      // into the constant pool.
798      THROW_MSG_0(vmSymbols::java_lang_NoClassDefFoundError(), name);
799    }
800    class_name = oopFactory::new_symbol_handle(name, str_len, CHECK_NULL);
801  }
802
803  ResourceMark rm(THREAD);
804  ClassFileStream st((u1*) buf, len, (char *)source);
805  Handle class_loader (THREAD, JNIHandles::resolve(loader));
806  if (UsePerfData) {
807    is_lock_held_by_thread(class_loader,
808                           ClassLoader::sync_JVMDefineClassLockFreeCounter(),
809                           THREAD);
810  }
811  Handle protection_domain (THREAD, JNIHandles::resolve(pd));
812  klassOop k = SystemDictionary::resolve_from_stream(class_name, class_loader,
813                                                     protection_domain, &st,
814                                                     verify != 0,
815                                                     CHECK_NULL);
816
817  if (TraceClassResolution && k != NULL) {
818    trace_class_resolution(k);
819  }
820
821  return (jclass) JNIHandles::make_local(env, Klass::cast(k)->java_mirror());
822}
823
824
825JVM_ENTRY(jclass, JVM_DefineClass(JNIEnv *env, const char *name, jobject loader, const jbyte *buf, jsize len, jobject pd))
826  JVMWrapper2("JVM_DefineClass %s", name);
827
828  return jvm_define_class_common(env, name, loader, buf, len, pd, NULL, true, THREAD);
829JVM_END
830
831
832JVM_ENTRY(jclass, JVM_DefineClassWithSource(JNIEnv *env, const char *name, jobject loader, const jbyte *buf, jsize len, jobject pd, const char *source))
833  JVMWrapper2("JVM_DefineClassWithSource %s", name);
834
835  return jvm_define_class_common(env, name, loader, buf, len, pd, source, true, THREAD);
836JVM_END
837
838JVM_ENTRY(jclass, JVM_DefineClassWithSourceCond(JNIEnv *env, const char *name,
839                                                jobject loader, const jbyte *buf,
840                                                jsize len, jobject pd,
841                                                const char *source, jboolean verify))
842  JVMWrapper2("JVM_DefineClassWithSourceCond %s", name);
843
844  return jvm_define_class_common(env, name, loader, buf, len, pd, source, verify, THREAD);
845JVM_END
846
847JVM_ENTRY(jclass, JVM_FindLoadedClass(JNIEnv *env, jobject loader, jstring name))
848  JVMWrapper("JVM_FindLoadedClass");
849  ResourceMark rm(THREAD);
850
851  Handle h_name (THREAD, JNIHandles::resolve_non_null(name));
852  Handle string = java_lang_String::internalize_classname(h_name, CHECK_NULL);
853
854  const char* str   = java_lang_String::as_utf8_string(string());
855  // Sanity check, don't expect null
856  if (str == NULL) return NULL;
857
858  const int str_len = (int)strlen(str);
859  if (str_len > symbolOopDesc::max_length()) {
860    // It's impossible to create this class;  the name cannot fit
861    // into the constant pool.
862    return NULL;
863  }
864  symbolHandle klass_name = oopFactory::new_symbol_handle(str, str_len,CHECK_NULL);
865
866  // Security Note:
867  //   The Java level wrapper will perform the necessary security check allowing
868  //   us to pass the NULL as the initiating class loader.
869  Handle h_loader(THREAD, JNIHandles::resolve(loader));
870  if (UsePerfData) {
871    is_lock_held_by_thread(h_loader,
872                           ClassLoader::sync_JVMFindLoadedClassLockFreeCounter(),
873                           THREAD);
874  }
875
876  klassOop k = SystemDictionary::find_instance_or_array_klass(klass_name,
877                                                              h_loader,
878                                                              Handle(),
879                                                              CHECK_NULL);
880
881  return (k == NULL) ? NULL :
882            (jclass) JNIHandles::make_local(env, Klass::cast(k)->java_mirror());
883JVM_END
884
885
886// Reflection support //////////////////////////////////////////////////////////////////////////////
887
888JVM_ENTRY(jstring, JVM_GetClassName(JNIEnv *env, jclass cls))
889  assert (cls != NULL, "illegal class");
890  JVMWrapper("JVM_GetClassName");
891  JvmtiVMObjectAllocEventCollector oam;
892  ResourceMark rm(THREAD);
893  const char* name;
894  if (java_lang_Class::is_primitive(JNIHandles::resolve(cls))) {
895    name = type2name(java_lang_Class::primitive_type(JNIHandles::resolve(cls)));
896  } else {
897    // Consider caching interned string in Klass
898    klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve(cls));
899    assert(k->is_klass(), "just checking");
900    name = Klass::cast(k)->external_name();
901  }
902  oop result = StringTable::intern((char*) name, CHECK_NULL);
903  return (jstring) JNIHandles::make_local(env, result);
904JVM_END
905
906
907JVM_ENTRY(jobjectArray, JVM_GetClassInterfaces(JNIEnv *env, jclass cls))
908  JVMWrapper("JVM_GetClassInterfaces");
909  JvmtiVMObjectAllocEventCollector oam;
910  oop mirror = JNIHandles::resolve_non_null(cls);
911
912  // Special handling for primitive objects
913  if (java_lang_Class::is_primitive(mirror)) {
914    // Primitive objects does not have any interfaces
915    objArrayOop r = oopFactory::new_objArray(SystemDictionary::Class_klass(), 0, CHECK_NULL);
916    return (jobjectArray) JNIHandles::make_local(env, r);
917  }
918
919  KlassHandle klass(thread, java_lang_Class::as_klassOop(mirror));
920  // Figure size of result array
921  int size;
922  if (klass->oop_is_instance()) {
923    size = instanceKlass::cast(klass())->local_interfaces()->length();
924  } else {
925    assert(klass->oop_is_objArray() || klass->oop_is_typeArray(), "Illegal mirror klass");
926    size = 2;
927  }
928
929  // Allocate result array
930  objArrayOop r = oopFactory::new_objArray(SystemDictionary::Class_klass(), size, CHECK_NULL);
931  objArrayHandle result (THREAD, r);
932  // Fill in result
933  if (klass->oop_is_instance()) {
934    // Regular instance klass, fill in all local interfaces
935    for (int index = 0; index < size; index++) {
936      klassOop k = klassOop(instanceKlass::cast(klass())->local_interfaces()->obj_at(index));
937      result->obj_at_put(index, Klass::cast(k)->java_mirror());
938    }
939  } else {
940    // All arrays implement java.lang.Cloneable and java.io.Serializable
941    result->obj_at_put(0, Klass::cast(SystemDictionary::Cloneable_klass())->java_mirror());
942    result->obj_at_put(1, Klass::cast(SystemDictionary::Serializable_klass())->java_mirror());
943  }
944  return (jobjectArray) JNIHandles::make_local(env, result());
945JVM_END
946
947
948JVM_ENTRY(jobject, JVM_GetClassLoader(JNIEnv *env, jclass cls))
949  JVMWrapper("JVM_GetClassLoader");
950  if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(cls))) {
951    return NULL;
952  }
953  klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls));
954  oop loader = Klass::cast(k)->class_loader();
955  return JNIHandles::make_local(env, loader);
956JVM_END
957
958
959JVM_QUICK_ENTRY(jboolean, JVM_IsInterface(JNIEnv *env, jclass cls))
960  JVMWrapper("JVM_IsInterface");
961  oop mirror = JNIHandles::resolve_non_null(cls);
962  if (java_lang_Class::is_primitive(mirror)) {
963    return JNI_FALSE;
964  }
965  klassOop k = java_lang_Class::as_klassOop(mirror);
966  jboolean result = Klass::cast(k)->is_interface();
967  assert(!result || Klass::cast(k)->oop_is_instance(),
968         "all interfaces are instance types");
969  // The compiler intrinsic for isInterface tests the
970  // Klass::_access_flags bits in the same way.
971  return result;
972JVM_END
973
974
975JVM_ENTRY(jobjectArray, JVM_GetClassSigners(JNIEnv *env, jclass cls))
976  JVMWrapper("JVM_GetClassSigners");
977  JvmtiVMObjectAllocEventCollector oam;
978  if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(cls))) {
979    // There are no signers for primitive types
980    return NULL;
981  }
982
983  klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls));
984  objArrayOop signers = NULL;
985  if (Klass::cast(k)->oop_is_instance()) {
986    signers = instanceKlass::cast(k)->signers();
987  }
988
989  // If there are no signers set in the class, or if the class
990  // is an array, return NULL.
991  if (signers == NULL) return NULL;
992
993  // copy of the signers array
994  klassOop element = objArrayKlass::cast(signers->klass())->element_klass();
995  objArrayOop signers_copy = oopFactory::new_objArray(element, signers->length(), CHECK_NULL);
996  for (int index = 0; index < signers->length(); index++) {
997    signers_copy->obj_at_put(index, signers->obj_at(index));
998  }
999
1000  // return the copy
1001  return (jobjectArray) JNIHandles::make_local(env, signers_copy);
1002JVM_END
1003
1004
1005JVM_ENTRY(void, JVM_SetClassSigners(JNIEnv *env, jclass cls, jobjectArray signers))
1006  JVMWrapper("JVM_SetClassSigners");
1007  if (!java_lang_Class::is_primitive(JNIHandles::resolve_non_null(cls))) {
1008    // This call is ignored for primitive types and arrays.
1009    // Signers are only set once, ClassLoader.java, and thus shouldn't
1010    // be called with an array.  Only the bootstrap loader creates arrays.
1011    klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls));
1012    if (Klass::cast(k)->oop_is_instance()) {
1013      instanceKlass::cast(k)->set_signers(objArrayOop(JNIHandles::resolve(signers)));
1014    }
1015  }
1016JVM_END
1017
1018
1019JVM_ENTRY(jobject, JVM_GetProtectionDomain(JNIEnv *env, jclass cls))
1020  JVMWrapper("JVM_GetProtectionDomain");
1021  if (JNIHandles::resolve(cls) == NULL) {
1022    THROW_(vmSymbols::java_lang_NullPointerException(), NULL);
1023  }
1024
1025  if (java_lang_Class::is_primitive(JNIHandles::resolve(cls))) {
1026    // Primitive types does not have a protection domain.
1027    return NULL;
1028  }
1029
1030  klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve(cls));
1031  return (jobject) JNIHandles::make_local(env, Klass::cast(k)->protection_domain());
1032JVM_END
1033
1034
1035// Obsolete since 1.2 (Class.setProtectionDomain removed), although
1036// still defined in core libraries as of 1.5.
1037JVM_ENTRY(void, JVM_SetProtectionDomain(JNIEnv *env, jclass cls, jobject protection_domain))
1038  JVMWrapper("JVM_SetProtectionDomain");
1039  if (JNIHandles::resolve(cls) == NULL) {
1040    THROW(vmSymbols::java_lang_NullPointerException());
1041  }
1042  if (!java_lang_Class::is_primitive(JNIHandles::resolve(cls))) {
1043    // Call is ignored for primitive types
1044    klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve(cls));
1045
1046    // cls won't be an array, as this called only from ClassLoader.defineClass
1047    if (Klass::cast(k)->oop_is_instance()) {
1048      oop pd = JNIHandles::resolve(protection_domain);
1049      assert(pd == NULL || pd->is_oop(), "just checking");
1050      instanceKlass::cast(k)->set_protection_domain(pd);
1051    }
1052  }
1053JVM_END
1054
1055
1056JVM_ENTRY(jobject, JVM_DoPrivileged(JNIEnv *env, jclass cls, jobject action, jobject context, jboolean wrapException))
1057  JVMWrapper("JVM_DoPrivileged");
1058
1059  if (action == NULL) {
1060    THROW_MSG_0(vmSymbols::java_lang_NullPointerException(), "Null action");
1061  }
1062
1063  // Stack allocated list of privileged stack elements
1064  PrivilegedElement pi;
1065
1066  // Check that action object understands "Object run()"
1067  Handle object (THREAD, JNIHandles::resolve(action));
1068
1069  // get run() method
1070  methodOop m_oop = Klass::cast(object->klass())->uncached_lookup_method(
1071                                           vmSymbols::run_method_name(),
1072                                           vmSymbols::void_object_signature());
1073  methodHandle m (THREAD, m_oop);
1074  if (m.is_null() || !m->is_method() || !methodOop(m())->is_public() || methodOop(m())->is_static()) {
1075    THROW_MSG_0(vmSymbols::java_lang_InternalError(), "No run method");
1076  }
1077
1078  // Compute the frame initiating the do privileged operation and setup the privileged stack
1079  vframeStream vfst(thread);
1080  vfst.security_get_caller_frame(1);
1081
1082  if (!vfst.at_end()) {
1083    pi.initialize(&vfst, JNIHandles::resolve(context), thread->privileged_stack_top(), CHECK_NULL);
1084    thread->set_privileged_stack_top(&pi);
1085  }
1086
1087
1088  // invoke the Object run() in the action object. We cannot use call_interface here, since the static type
1089  // is not really known - it is either java.security.PrivilegedAction or java.security.PrivilegedExceptionAction
1090  Handle pending_exception;
1091  JavaValue result(T_OBJECT);
1092  JavaCallArguments args(object);
1093  JavaCalls::call(&result, m, &args, THREAD);
1094
1095  // done with action, remove ourselves from the list
1096  if (!vfst.at_end()) {
1097    assert(thread->privileged_stack_top() != NULL && thread->privileged_stack_top() == &pi, "wrong top element");
1098    thread->set_privileged_stack_top(thread->privileged_stack_top()->next());
1099  }
1100
1101  if (HAS_PENDING_EXCEPTION) {
1102    pending_exception = Handle(THREAD, PENDING_EXCEPTION);
1103    CLEAR_PENDING_EXCEPTION;
1104
1105    if ( pending_exception->is_a(SystemDictionary::Exception_klass()) &&
1106        !pending_exception->is_a(SystemDictionary::RuntimeException_klass())) {
1107      // Throw a java.security.PrivilegedActionException(Exception e) exception
1108      JavaCallArguments args(pending_exception);
1109      THROW_ARG_0(vmSymbolHandles::java_security_PrivilegedActionException(),
1110                  vmSymbolHandles::exception_void_signature(),
1111                  &args);
1112    }
1113  }
1114
1115  if (pending_exception.not_null()) THROW_OOP_0(pending_exception());
1116  return JNIHandles::make_local(env, (oop) result.get_jobject());
1117JVM_END
1118
1119
1120// Returns the inherited_access_control_context field of the running thread.
1121JVM_ENTRY(jobject, JVM_GetInheritedAccessControlContext(JNIEnv *env, jclass cls))
1122  JVMWrapper("JVM_GetInheritedAccessControlContext");
1123  oop result = java_lang_Thread::inherited_access_control_context(thread->threadObj());
1124  return JNIHandles::make_local(env, result);
1125JVM_END
1126
1127class RegisterArrayForGC {
1128 private:
1129  JavaThread *_thread;
1130 public:
1131  RegisterArrayForGC(JavaThread *thread, GrowableArray<oop>* array)  {
1132    _thread = thread;
1133    _thread->register_array_for_gc(array);
1134  }
1135
1136  ~RegisterArrayForGC() {
1137    _thread->register_array_for_gc(NULL);
1138  }
1139};
1140
1141
1142JVM_ENTRY(jobject, JVM_GetStackAccessControlContext(JNIEnv *env, jclass cls))
1143  JVMWrapper("JVM_GetStackAccessControlContext");
1144  if (!UsePrivilegedStack) return NULL;
1145
1146  ResourceMark rm(THREAD);
1147  GrowableArray<oop>* local_array = new GrowableArray<oop>(12);
1148  JvmtiVMObjectAllocEventCollector oam;
1149
1150  // count the protection domains on the execution stack. We collapse
1151  // duplicate consecutive protection domains into a single one, as
1152  // well as stopping when we hit a privileged frame.
1153
1154  // Use vframeStream to iterate through Java frames
1155  vframeStream vfst(thread);
1156
1157  oop previous_protection_domain = NULL;
1158  Handle privileged_context(thread, NULL);
1159  bool is_privileged = false;
1160  oop protection_domain = NULL;
1161
1162  for(; !vfst.at_end(); vfst.next()) {
1163    // get method of frame
1164    methodOop method = vfst.method();
1165    intptr_t* frame_id   = vfst.frame_id();
1166
1167    // check the privileged frames to see if we have a match
1168    if (thread->privileged_stack_top() && thread->privileged_stack_top()->frame_id() == frame_id) {
1169      // this frame is privileged
1170      is_privileged = true;
1171      privileged_context = Handle(thread, thread->privileged_stack_top()->privileged_context());
1172      protection_domain  = thread->privileged_stack_top()->protection_domain();
1173    } else {
1174      protection_domain = instanceKlass::cast(method->method_holder())->protection_domain();
1175    }
1176
1177    if ((previous_protection_domain != protection_domain) && (protection_domain != NULL)) {
1178      local_array->push(protection_domain);
1179      previous_protection_domain = protection_domain;
1180    }
1181
1182    if (is_privileged) break;
1183  }
1184
1185
1186  // either all the domains on the stack were system domains, or
1187  // we had a privileged system domain
1188  if (local_array->is_empty()) {
1189    if (is_privileged && privileged_context.is_null()) return NULL;
1190
1191    oop result = java_security_AccessControlContext::create(objArrayHandle(), is_privileged, privileged_context, CHECK_NULL);
1192    return JNIHandles::make_local(env, result);
1193  }
1194
1195  // the resource area must be registered in case of a gc
1196  RegisterArrayForGC ragc(thread, local_array);
1197  objArrayOop context = oopFactory::new_objArray(SystemDictionary::ProtectionDomain_klass(),
1198                                                 local_array->length(), CHECK_NULL);
1199  objArrayHandle h_context(thread, context);
1200  for (int index = 0; index < local_array->length(); index++) {
1201    h_context->obj_at_put(index, local_array->at(index));
1202  }
1203
1204  oop result = java_security_AccessControlContext::create(h_context, is_privileged, privileged_context, CHECK_NULL);
1205
1206  return JNIHandles::make_local(env, result);
1207JVM_END
1208
1209
1210JVM_QUICK_ENTRY(jboolean, JVM_IsArrayClass(JNIEnv *env, jclass cls))
1211  JVMWrapper("JVM_IsArrayClass");
1212  klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls));
1213  return (k != NULL) && Klass::cast(k)->oop_is_javaArray() ? true : false;
1214JVM_END
1215
1216
1217JVM_QUICK_ENTRY(jboolean, JVM_IsPrimitiveClass(JNIEnv *env, jclass cls))
1218  JVMWrapper("JVM_IsPrimitiveClass");
1219  oop mirror = JNIHandles::resolve_non_null(cls);
1220  return (jboolean) java_lang_Class::is_primitive(mirror);
1221JVM_END
1222
1223
1224JVM_ENTRY(jclass, JVM_GetComponentType(JNIEnv *env, jclass cls))
1225  JVMWrapper("JVM_GetComponentType");
1226  oop mirror = JNIHandles::resolve_non_null(cls);
1227  oop result = Reflection::array_component_type(mirror, CHECK_NULL);
1228  return (jclass) JNIHandles::make_local(env, result);
1229JVM_END
1230
1231
1232JVM_ENTRY(jint, JVM_GetClassModifiers(JNIEnv *env, jclass cls))
1233  JVMWrapper("JVM_GetClassModifiers");
1234  if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(cls))) {
1235    // Primitive type
1236    return JVM_ACC_ABSTRACT | JVM_ACC_FINAL | JVM_ACC_PUBLIC;
1237  }
1238
1239  Klass* k = Klass::cast(java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls)));
1240  debug_only(int computed_modifiers = k->compute_modifier_flags(CHECK_0));
1241  assert(k->modifier_flags() == computed_modifiers, "modifiers cache is OK");
1242  return k->modifier_flags();
1243JVM_END
1244
1245
1246// Inner class reflection ///////////////////////////////////////////////////////////////////////////////
1247
1248JVM_ENTRY(jobjectArray, JVM_GetDeclaredClasses(JNIEnv *env, jclass ofClass))
1249  const int inner_class_info_index = 0;
1250  const int outer_class_info_index = 1;
1251
1252  JvmtiVMObjectAllocEventCollector oam;
1253  // ofClass is a reference to a java_lang_Class object. The mirror object
1254  // of an instanceKlass
1255
1256  if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(ofClass)) ||
1257      ! Klass::cast(java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(ofClass)))->oop_is_instance()) {
1258    oop result = oopFactory::new_objArray(SystemDictionary::Class_klass(), 0, CHECK_NULL);
1259    return (jobjectArray)JNIHandles::make_local(env, result);
1260  }
1261
1262  instanceKlassHandle k(thread, java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(ofClass)));
1263
1264  if (k->inner_classes()->length() == 0) {
1265    // Neither an inner nor outer class
1266    oop result = oopFactory::new_objArray(SystemDictionary::Class_klass(), 0, CHECK_NULL);
1267    return (jobjectArray)JNIHandles::make_local(env, result);
1268  }
1269
1270  // find inner class info
1271  typeArrayHandle    icls(thread, k->inner_classes());
1272  constantPoolHandle cp(thread, k->constants());
1273  int length = icls->length();
1274
1275  // Allocate temp. result array
1276  objArrayOop r = oopFactory::new_objArray(SystemDictionary::Class_klass(), length/4, CHECK_NULL);
1277  objArrayHandle result (THREAD, r);
1278  int members = 0;
1279
1280  for(int i = 0; i < length; i += 4) {
1281    int ioff = icls->ushort_at(i + inner_class_info_index);
1282    int ooff = icls->ushort_at(i + outer_class_info_index);
1283
1284    if (ioff != 0 && ooff != 0) {
1285      // Check to see if the name matches the class we're looking for
1286      // before attempting to find the class.
1287      if (cp->klass_name_at_matches(k, ooff)) {
1288        klassOop outer_klass = cp->klass_at(ooff, CHECK_NULL);
1289        if (outer_klass == k()) {
1290           klassOop ik = cp->klass_at(ioff, CHECK_NULL);
1291           instanceKlassHandle inner_klass (THREAD, ik);
1292
1293           // Throws an exception if outer klass has not declared k as
1294           // an inner klass
1295           Reflection::check_for_inner_class(k, inner_klass, true, CHECK_NULL);
1296
1297           result->obj_at_put(members, inner_klass->java_mirror());
1298           members++;
1299        }
1300      }
1301    }
1302  }
1303
1304  if (members != length) {
1305    // Return array of right length
1306    objArrayOop res = oopFactory::new_objArray(SystemDictionary::Class_klass(), members, CHECK_NULL);
1307    for(int i = 0; i < members; i++) {
1308      res->obj_at_put(i, result->obj_at(i));
1309    }
1310    return (jobjectArray)JNIHandles::make_local(env, res);
1311  }
1312
1313  return (jobjectArray)JNIHandles::make_local(env, result());
1314JVM_END
1315
1316
1317JVM_ENTRY(jclass, JVM_GetDeclaringClass(JNIEnv *env, jclass ofClass))
1318{
1319  // ofClass is a reference to a java_lang_Class object.
1320  if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(ofClass)) ||
1321      ! Klass::cast(java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(ofClass)))->oop_is_instance()) {
1322    return NULL;
1323  }
1324
1325  bool inner_is_member = false;
1326  klassOop outer_klass
1327    = instanceKlass::cast(java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(ofClass))
1328                          )->compute_enclosing_class(&inner_is_member, CHECK_NULL);
1329  if (outer_klass == NULL)  return NULL;  // already a top-level class
1330  if (!inner_is_member)  return NULL;     // an anonymous class (inside a method)
1331  return (jclass) JNIHandles::make_local(env, Klass::cast(outer_klass)->java_mirror());
1332}
1333JVM_END
1334
1335// should be in instanceKlass.cpp, but is here for historical reasons
1336klassOop instanceKlass::compute_enclosing_class_impl(instanceKlassHandle k,
1337                                                     bool* inner_is_member,
1338                                                     TRAPS) {
1339  Thread* thread = THREAD;
1340  const int inner_class_info_index = inner_class_inner_class_info_offset;
1341  const int outer_class_info_index = inner_class_outer_class_info_offset;
1342
1343  if (k->inner_classes()->length() == 0) {
1344    // No inner class info => no declaring class
1345    return NULL;
1346  }
1347
1348  typeArrayHandle i_icls(thread, k->inner_classes());
1349  constantPoolHandle i_cp(thread, k->constants());
1350  int i_length = i_icls->length();
1351
1352  bool found = false;
1353  klassOop ok;
1354  instanceKlassHandle outer_klass;
1355  *inner_is_member = false;
1356
1357  // Find inner_klass attribute
1358  for (int i = 0; i < i_length && !found; i += inner_class_next_offset) {
1359    int ioff = i_icls->ushort_at(i + inner_class_info_index);
1360    int ooff = i_icls->ushort_at(i + outer_class_info_index);
1361    int noff = i_icls->ushort_at(i + inner_class_inner_name_offset);
1362    if (ioff != 0) {
1363      // Check to see if the name matches the class we're looking for
1364      // before attempting to find the class.
1365      if (i_cp->klass_name_at_matches(k, ioff)) {
1366        klassOop inner_klass = i_cp->klass_at(ioff, CHECK_NULL);
1367        found = (k() == inner_klass);
1368        if (found && ooff != 0) {
1369          ok = i_cp->klass_at(ooff, CHECK_NULL);
1370          outer_klass = instanceKlassHandle(thread, ok);
1371          *inner_is_member = true;
1372        }
1373      }
1374    }
1375  }
1376
1377  if (found && outer_klass.is_null()) {
1378    // It may be anonymous; try for that.
1379    int encl_method_class_idx = k->enclosing_method_class_index();
1380    if (encl_method_class_idx != 0) {
1381      ok = i_cp->klass_at(encl_method_class_idx, CHECK_NULL);
1382      outer_klass = instanceKlassHandle(thread, ok);
1383      *inner_is_member = false;
1384    }
1385  }
1386
1387  // If no inner class attribute found for this class.
1388  if (outer_klass.is_null())  return NULL;
1389
1390  // Throws an exception if outer klass has not declared k as an inner klass
1391  // We need evidence that each klass knows about the other, or else
1392  // the system could allow a spoof of an inner class to gain access rights.
1393  Reflection::check_for_inner_class(outer_klass, k, *inner_is_member, CHECK_NULL);
1394  return outer_klass();
1395}
1396
1397JVM_ENTRY(jstring, JVM_GetClassSignature(JNIEnv *env, jclass cls))
1398  assert (cls != NULL, "illegal class");
1399  JVMWrapper("JVM_GetClassSignature");
1400  JvmtiVMObjectAllocEventCollector oam;
1401  ResourceMark rm(THREAD);
1402  // Return null for arrays and primatives
1403  if (!java_lang_Class::is_primitive(JNIHandles::resolve(cls))) {
1404    klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve(cls));
1405    if (Klass::cast(k)->oop_is_instance()) {
1406      symbolHandle sym = symbolHandle(THREAD, instanceKlass::cast(k)->generic_signature());
1407      if (sym.is_null()) return NULL;
1408      Handle str = java_lang_String::create_from_symbol(sym, CHECK_NULL);
1409      return (jstring) JNIHandles::make_local(env, str());
1410    }
1411  }
1412  return NULL;
1413JVM_END
1414
1415
1416JVM_ENTRY(jbyteArray, JVM_GetClassAnnotations(JNIEnv *env, jclass cls))
1417  assert (cls != NULL, "illegal class");
1418  JVMWrapper("JVM_GetClassAnnotations");
1419  ResourceMark rm(THREAD);
1420  // Return null for arrays and primitives
1421  if (!java_lang_Class::is_primitive(JNIHandles::resolve(cls))) {
1422    klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve(cls));
1423    if (Klass::cast(k)->oop_is_instance()) {
1424      return (jbyteArray) JNIHandles::make_local(env,
1425                                  instanceKlass::cast(k)->class_annotations());
1426    }
1427  }
1428  return NULL;
1429JVM_END
1430
1431
1432JVM_ENTRY(jbyteArray, JVM_GetFieldAnnotations(JNIEnv *env, jobject field))
1433  assert(field != NULL, "illegal field");
1434  JVMWrapper("JVM_GetFieldAnnotations");
1435
1436  // some of this code was adapted from from jni_FromReflectedField
1437
1438  // field is a handle to a java.lang.reflect.Field object
1439  oop reflected = JNIHandles::resolve_non_null(field);
1440  oop mirror    = java_lang_reflect_Field::clazz(reflected);
1441  klassOop k    = java_lang_Class::as_klassOop(mirror);
1442  int slot      = java_lang_reflect_Field::slot(reflected);
1443  int modifiers = java_lang_reflect_Field::modifiers(reflected);
1444
1445  fieldDescriptor fd;
1446  KlassHandle kh(THREAD, k);
1447  intptr_t offset = instanceKlass::cast(kh())->offset_from_fields(slot);
1448
1449  if (modifiers & JVM_ACC_STATIC) {
1450    // for static fields we only look in the current class
1451    if (!instanceKlass::cast(kh())->find_local_field_from_offset(offset,
1452                                                                 true, &fd)) {
1453      assert(false, "cannot find static field");
1454      return NULL;  // robustness
1455    }
1456  } else {
1457    // for instance fields we start with the current class and work
1458    // our way up through the superclass chain
1459    if (!instanceKlass::cast(kh())->find_field_from_offset(offset, false,
1460                                                           &fd)) {
1461      assert(false, "cannot find instance field");
1462      return NULL;  // robustness
1463    }
1464  }
1465
1466  return (jbyteArray) JNIHandles::make_local(env, fd.annotations());
1467JVM_END
1468
1469
1470static methodOop jvm_get_method_common(jobject method, TRAPS) {
1471  // some of this code was adapted from from jni_FromReflectedMethod
1472
1473  oop reflected = JNIHandles::resolve_non_null(method);
1474  oop mirror    = NULL;
1475  int slot      = 0;
1476
1477  if (reflected->klass() == SystemDictionary::reflect_Constructor_klass()) {
1478    mirror = java_lang_reflect_Constructor::clazz(reflected);
1479    slot   = java_lang_reflect_Constructor::slot(reflected);
1480  } else {
1481    assert(reflected->klass() == SystemDictionary::reflect_Method_klass(),
1482           "wrong type");
1483    mirror = java_lang_reflect_Method::clazz(reflected);
1484    slot   = java_lang_reflect_Method::slot(reflected);
1485  }
1486  klassOop k = java_lang_Class::as_klassOop(mirror);
1487
1488  KlassHandle kh(THREAD, k);
1489  methodOop m = instanceKlass::cast(kh())->method_with_idnum(slot);
1490  if (m == NULL) {
1491    assert(false, "cannot find method");
1492    return NULL;  // robustness
1493  }
1494
1495  return m;
1496}
1497
1498
1499JVM_ENTRY(jbyteArray, JVM_GetMethodAnnotations(JNIEnv *env, jobject method))
1500  JVMWrapper("JVM_GetMethodAnnotations");
1501
1502  // method is a handle to a java.lang.reflect.Method object
1503  methodOop m = jvm_get_method_common(method, CHECK_NULL);
1504  return (jbyteArray) JNIHandles::make_local(env, m->annotations());
1505JVM_END
1506
1507
1508JVM_ENTRY(jbyteArray, JVM_GetMethodDefaultAnnotationValue(JNIEnv *env, jobject method))
1509  JVMWrapper("JVM_GetMethodDefaultAnnotationValue");
1510
1511  // method is a handle to a java.lang.reflect.Method object
1512  methodOop m = jvm_get_method_common(method, CHECK_NULL);
1513  return (jbyteArray) JNIHandles::make_local(env, m->annotation_default());
1514JVM_END
1515
1516
1517JVM_ENTRY(jbyteArray, JVM_GetMethodParameterAnnotations(JNIEnv *env, jobject method))
1518  JVMWrapper("JVM_GetMethodParameterAnnotations");
1519
1520  // method is a handle to a java.lang.reflect.Method object
1521  methodOop m = jvm_get_method_common(method, CHECK_NULL);
1522  return (jbyteArray) JNIHandles::make_local(env, m->parameter_annotations());
1523JVM_END
1524
1525
1526// New (JDK 1.4) reflection implementation /////////////////////////////////////
1527
1528JVM_ENTRY(jobjectArray, JVM_GetClassDeclaredFields(JNIEnv *env, jclass ofClass, jboolean publicOnly))
1529{
1530  JVMWrapper("JVM_GetClassDeclaredFields");
1531  JvmtiVMObjectAllocEventCollector oam;
1532
1533  // Exclude primitive types and array types
1534  if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(ofClass)) ||
1535      Klass::cast(java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(ofClass)))->oop_is_javaArray()) {
1536    // Return empty array
1537    oop res = oopFactory::new_objArray(SystemDictionary::reflect_Field_klass(), 0, CHECK_NULL);
1538    return (jobjectArray) JNIHandles::make_local(env, res);
1539  }
1540
1541  instanceKlassHandle k(THREAD, java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(ofClass)));
1542  constantPoolHandle cp(THREAD, k->constants());
1543
1544  // Ensure class is linked
1545  k->link_class(CHECK_NULL);
1546
1547  typeArrayHandle fields(THREAD, k->fields());
1548  int fields_len = fields->length();
1549
1550  // 4496456 We need to filter out java.lang.Throwable.backtrace
1551  bool skip_backtrace = false;
1552
1553  // Allocate result
1554  int num_fields;
1555
1556  if (publicOnly) {
1557    num_fields = 0;
1558    for (int i = 0, j = 0; i < fields_len; i += instanceKlass::next_offset, j++) {
1559      int mods = fields->ushort_at(i + instanceKlass::access_flags_offset) & JVM_RECOGNIZED_FIELD_MODIFIERS;
1560      if (mods & JVM_ACC_PUBLIC) ++num_fields;
1561    }
1562  } else {
1563    num_fields = fields_len / instanceKlass::next_offset;
1564
1565    if (k() == SystemDictionary::Throwable_klass()) {
1566      num_fields--;
1567      skip_backtrace = true;
1568    }
1569  }
1570
1571  objArrayOop r = oopFactory::new_objArray(SystemDictionary::reflect_Field_klass(), num_fields, CHECK_NULL);
1572  objArrayHandle result (THREAD, r);
1573
1574  int out_idx = 0;
1575  fieldDescriptor fd;
1576  for (int i = 0; i < fields_len; i += instanceKlass::next_offset) {
1577    if (skip_backtrace) {
1578      // 4496456 skip java.lang.Throwable.backtrace
1579      int offset = k->offset_from_fields(i);
1580      if (offset == java_lang_Throwable::get_backtrace_offset()) continue;
1581    }
1582
1583    int mods = fields->ushort_at(i + instanceKlass::access_flags_offset) & JVM_RECOGNIZED_FIELD_MODIFIERS;
1584    if (!publicOnly || (mods & JVM_ACC_PUBLIC)) {
1585      fd.initialize(k(), i);
1586      oop field = Reflection::new_field(&fd, UseNewReflection, CHECK_NULL);
1587      result->obj_at_put(out_idx, field);
1588      ++out_idx;
1589    }
1590  }
1591  assert(out_idx == num_fields, "just checking");
1592  return (jobjectArray) JNIHandles::make_local(env, result());
1593}
1594JVM_END
1595
1596JVM_ENTRY(jobjectArray, JVM_GetClassDeclaredMethods(JNIEnv *env, jclass ofClass, jboolean publicOnly))
1597{
1598  JVMWrapper("JVM_GetClassDeclaredMethods");
1599  JvmtiVMObjectAllocEventCollector oam;
1600
1601  // Exclude primitive types and array types
1602  if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(ofClass))
1603      || Klass::cast(java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(ofClass)))->oop_is_javaArray()) {
1604    // Return empty array
1605    oop res = oopFactory::new_objArray(SystemDictionary::reflect_Method_klass(), 0, CHECK_NULL);
1606    return (jobjectArray) JNIHandles::make_local(env, res);
1607  }
1608
1609  instanceKlassHandle k(THREAD, java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(ofClass)));
1610
1611  // Ensure class is linked
1612  k->link_class(CHECK_NULL);
1613
1614  objArrayHandle methods (THREAD, k->methods());
1615  int methods_length = methods->length();
1616  int num_methods = 0;
1617
1618  int i;
1619  for (i = 0; i < methods_length; i++) {
1620    methodHandle method(THREAD, (methodOop) methods->obj_at(i));
1621    if (!method->is_initializer()) {
1622      if (!publicOnly || method->is_public()) {
1623        ++num_methods;
1624      }
1625    }
1626  }
1627
1628  // Allocate result
1629  objArrayOop r = oopFactory::new_objArray(SystemDictionary::reflect_Method_klass(), num_methods, CHECK_NULL);
1630  objArrayHandle result (THREAD, r);
1631
1632  int out_idx = 0;
1633  for (i = 0; i < methods_length; i++) {
1634    methodHandle method(THREAD, (methodOop) methods->obj_at(i));
1635    if (!method->is_initializer()) {
1636      if (!publicOnly || method->is_public()) {
1637        oop m = Reflection::new_method(method, UseNewReflection, false, CHECK_NULL);
1638        result->obj_at_put(out_idx, m);
1639        ++out_idx;
1640      }
1641    }
1642  }
1643  assert(out_idx == num_methods, "just checking");
1644  return (jobjectArray) JNIHandles::make_local(env, result());
1645}
1646JVM_END
1647
1648JVM_ENTRY(jobjectArray, JVM_GetClassDeclaredConstructors(JNIEnv *env, jclass ofClass, jboolean publicOnly))
1649{
1650  JVMWrapper("JVM_GetClassDeclaredConstructors");
1651  JvmtiVMObjectAllocEventCollector oam;
1652
1653  // Exclude primitive types and array types
1654  if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(ofClass))
1655      || Klass::cast(java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(ofClass)))->oop_is_javaArray()) {
1656    // Return empty array
1657    oop res = oopFactory::new_objArray(SystemDictionary::reflect_Constructor_klass(), 0 , CHECK_NULL);
1658    return (jobjectArray) JNIHandles::make_local(env, res);
1659  }
1660
1661  instanceKlassHandle k(THREAD, java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(ofClass)));
1662
1663  // Ensure class is linked
1664  k->link_class(CHECK_NULL);
1665
1666  objArrayHandle methods (THREAD, k->methods());
1667  int methods_length = methods->length();
1668  int num_constructors = 0;
1669
1670  int i;
1671  for (i = 0; i < methods_length; i++) {
1672    methodHandle method(THREAD, (methodOop) methods->obj_at(i));
1673    if (method->is_initializer() && !method->is_static()) {
1674      if (!publicOnly || method->is_public()) {
1675        ++num_constructors;
1676      }
1677    }
1678  }
1679
1680  // Allocate result
1681  objArrayOop r = oopFactory::new_objArray(SystemDictionary::reflect_Constructor_klass(), num_constructors, CHECK_NULL);
1682  objArrayHandle result(THREAD, r);
1683
1684  int out_idx = 0;
1685  for (i = 0; i < methods_length; i++) {
1686    methodHandle method(THREAD, (methodOop) methods->obj_at(i));
1687    if (method->is_initializer() && !method->is_static()) {
1688      if (!publicOnly || method->is_public()) {
1689        oop m = Reflection::new_constructor(method, CHECK_NULL);
1690        result->obj_at_put(out_idx, m);
1691        ++out_idx;
1692      }
1693    }
1694  }
1695  assert(out_idx == num_constructors, "just checking");
1696  return (jobjectArray) JNIHandles::make_local(env, result());
1697}
1698JVM_END
1699
1700JVM_ENTRY(jint, JVM_GetClassAccessFlags(JNIEnv *env, jclass cls))
1701{
1702  JVMWrapper("JVM_GetClassAccessFlags");
1703  if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(cls))) {
1704    // Primitive type
1705    return JVM_ACC_ABSTRACT | JVM_ACC_FINAL | JVM_ACC_PUBLIC;
1706  }
1707
1708  Klass* k = Klass::cast(java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls)));
1709  return k->access_flags().as_int() & JVM_ACC_WRITTEN_FLAGS;
1710}
1711JVM_END
1712
1713
1714// Constant pool access //////////////////////////////////////////////////////////
1715
1716JVM_ENTRY(jobject, JVM_GetClassConstantPool(JNIEnv *env, jclass cls))
1717{
1718  JVMWrapper("JVM_GetClassConstantPool");
1719  JvmtiVMObjectAllocEventCollector oam;
1720
1721  // Return null for primitives and arrays
1722  if (!java_lang_Class::is_primitive(JNIHandles::resolve_non_null(cls))) {
1723    klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls));
1724    if (Klass::cast(k)->oop_is_instance()) {
1725      instanceKlassHandle k_h(THREAD, k);
1726      Handle jcp = sun_reflect_ConstantPool::create(CHECK_NULL);
1727      sun_reflect_ConstantPool::set_cp_oop(jcp(), k_h->constants());
1728      return JNIHandles::make_local(jcp());
1729    }
1730  }
1731  return NULL;
1732}
1733JVM_END
1734
1735
1736JVM_ENTRY(jint, JVM_ConstantPoolGetSize(JNIEnv *env, jobject unused, jobject jcpool))
1737{
1738  JVMWrapper("JVM_ConstantPoolGetSize");
1739  constantPoolHandle cp = constantPoolHandle(THREAD, constantPoolOop(JNIHandles::resolve_non_null(jcpool)));
1740  return cp->length();
1741}
1742JVM_END
1743
1744
1745static void bounds_check(constantPoolHandle cp, jint index, TRAPS) {
1746  if (!cp->is_within_bounds(index)) {
1747    THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "Constant pool index out of bounds");
1748  }
1749}
1750
1751
1752JVM_ENTRY(jclass, JVM_ConstantPoolGetClassAt(JNIEnv *env, jobject unused, jobject jcpool, jint index))
1753{
1754  JVMWrapper("JVM_ConstantPoolGetClassAt");
1755  constantPoolHandle cp = constantPoolHandle(THREAD, constantPoolOop(JNIHandles::resolve_non_null(jcpool)));
1756  bounds_check(cp, index, CHECK_NULL);
1757  constantTag tag = cp->tag_at(index);
1758  if (!tag.is_klass() && !tag.is_unresolved_klass()) {
1759    THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
1760  }
1761  klassOop k = cp->klass_at(index, CHECK_NULL);
1762  return (jclass) JNIHandles::make_local(k->klass_part()->java_mirror());
1763}
1764JVM_END
1765
1766
1767JVM_ENTRY(jclass, JVM_ConstantPoolGetClassAtIfLoaded(JNIEnv *env, jobject unused, jobject jcpool, jint index))
1768{
1769  JVMWrapper("JVM_ConstantPoolGetClassAtIfLoaded");
1770  constantPoolHandle cp = constantPoolHandle(THREAD, constantPoolOop(JNIHandles::resolve_non_null(jcpool)));
1771  bounds_check(cp, index, CHECK_NULL);
1772  constantTag tag = cp->tag_at(index);
1773  if (!tag.is_klass() && !tag.is_unresolved_klass()) {
1774    THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
1775  }
1776  klassOop k = constantPoolOopDesc::klass_at_if_loaded(cp, index);
1777  if (k == NULL) return NULL;
1778  return (jclass) JNIHandles::make_local(k->klass_part()->java_mirror());
1779}
1780JVM_END
1781
1782static jobject get_method_at_helper(constantPoolHandle cp, jint index, bool force_resolution, TRAPS) {
1783  constantTag tag = cp->tag_at(index);
1784  if (!tag.is_method() && !tag.is_interface_method()) {
1785    THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
1786  }
1787  int klass_ref  = cp->uncached_klass_ref_index_at(index);
1788  klassOop k_o;
1789  if (force_resolution) {
1790    k_o = cp->klass_at(klass_ref, CHECK_NULL);
1791  } else {
1792    k_o = constantPoolOopDesc::klass_at_if_loaded(cp, klass_ref);
1793    if (k_o == NULL) return NULL;
1794  }
1795  instanceKlassHandle k(THREAD, k_o);
1796  symbolOop name = cp->uncached_name_ref_at(index);
1797  symbolOop sig  = cp->uncached_signature_ref_at(index);
1798  methodHandle m (THREAD, k->find_method(name, sig));
1799  if (m.is_null()) {
1800    THROW_MSG_0(vmSymbols::java_lang_RuntimeException(), "Unable to look up method in target class");
1801  }
1802  oop method;
1803  if (!m->is_initializer() || m->is_static()) {
1804    method = Reflection::new_method(m, true, true, CHECK_NULL);
1805  } else {
1806    method = Reflection::new_constructor(m, CHECK_NULL);
1807  }
1808  return JNIHandles::make_local(method);
1809}
1810
1811JVM_ENTRY(jobject, JVM_ConstantPoolGetMethodAt(JNIEnv *env, jobject unused, jobject jcpool, jint index))
1812{
1813  JVMWrapper("JVM_ConstantPoolGetMethodAt");
1814  JvmtiVMObjectAllocEventCollector oam;
1815  constantPoolHandle cp = constantPoolHandle(THREAD, constantPoolOop(JNIHandles::resolve_non_null(jcpool)));
1816  bounds_check(cp, index, CHECK_NULL);
1817  jobject res = get_method_at_helper(cp, index, true, CHECK_NULL);
1818  return res;
1819}
1820JVM_END
1821
1822JVM_ENTRY(jobject, JVM_ConstantPoolGetMethodAtIfLoaded(JNIEnv *env, jobject unused, jobject jcpool, jint index))
1823{
1824  JVMWrapper("JVM_ConstantPoolGetMethodAtIfLoaded");
1825  JvmtiVMObjectAllocEventCollector oam;
1826  constantPoolHandle cp = constantPoolHandle(THREAD, constantPoolOop(JNIHandles::resolve_non_null(jcpool)));
1827  bounds_check(cp, index, CHECK_NULL);
1828  jobject res = get_method_at_helper(cp, index, false, CHECK_NULL);
1829  return res;
1830}
1831JVM_END
1832
1833static jobject get_field_at_helper(constantPoolHandle cp, jint index, bool force_resolution, TRAPS) {
1834  constantTag tag = cp->tag_at(index);
1835  if (!tag.is_field()) {
1836    THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
1837  }
1838  int klass_ref  = cp->uncached_klass_ref_index_at(index);
1839  klassOop k_o;
1840  if (force_resolution) {
1841    k_o = cp->klass_at(klass_ref, CHECK_NULL);
1842  } else {
1843    k_o = constantPoolOopDesc::klass_at_if_loaded(cp, klass_ref);
1844    if (k_o == NULL) return NULL;
1845  }
1846  instanceKlassHandle k(THREAD, k_o);
1847  symbolOop name = cp->uncached_name_ref_at(index);
1848  symbolOop sig  = cp->uncached_signature_ref_at(index);
1849  fieldDescriptor fd;
1850  klassOop target_klass = k->find_field(name, sig, &fd);
1851  if (target_klass == NULL) {
1852    THROW_MSG_0(vmSymbols::java_lang_RuntimeException(), "Unable to look up field in target class");
1853  }
1854  oop field = Reflection::new_field(&fd, true, CHECK_NULL);
1855  return JNIHandles::make_local(field);
1856}
1857
1858JVM_ENTRY(jobject, JVM_ConstantPoolGetFieldAt(JNIEnv *env, jobject unused, jobject jcpool, jint index))
1859{
1860  JVMWrapper("JVM_ConstantPoolGetFieldAt");
1861  JvmtiVMObjectAllocEventCollector oam;
1862  constantPoolHandle cp = constantPoolHandle(THREAD, constantPoolOop(JNIHandles::resolve_non_null(jcpool)));
1863  bounds_check(cp, index, CHECK_NULL);
1864  jobject res = get_field_at_helper(cp, index, true, CHECK_NULL);
1865  return res;
1866}
1867JVM_END
1868
1869JVM_ENTRY(jobject, JVM_ConstantPoolGetFieldAtIfLoaded(JNIEnv *env, jobject unused, jobject jcpool, jint index))
1870{
1871  JVMWrapper("JVM_ConstantPoolGetFieldAtIfLoaded");
1872  JvmtiVMObjectAllocEventCollector oam;
1873  constantPoolHandle cp = constantPoolHandle(THREAD, constantPoolOop(JNIHandles::resolve_non_null(jcpool)));
1874  bounds_check(cp, index, CHECK_NULL);
1875  jobject res = get_field_at_helper(cp, index, false, CHECK_NULL);
1876  return res;
1877}
1878JVM_END
1879
1880JVM_ENTRY(jobjectArray, JVM_ConstantPoolGetMemberRefInfoAt(JNIEnv *env, jobject unused, jobject jcpool, jint index))
1881{
1882  JVMWrapper("JVM_ConstantPoolGetMemberRefInfoAt");
1883  JvmtiVMObjectAllocEventCollector oam;
1884  constantPoolHandle cp = constantPoolHandle(THREAD, constantPoolOop(JNIHandles::resolve_non_null(jcpool)));
1885  bounds_check(cp, index, CHECK_NULL);
1886  constantTag tag = cp->tag_at(index);
1887  if (!tag.is_field_or_method()) {
1888    THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
1889  }
1890  int klass_ref = cp->uncached_klass_ref_index_at(index);
1891  symbolHandle klass_name (THREAD, cp->klass_name_at(klass_ref));
1892  symbolHandle member_name(THREAD, cp->uncached_name_ref_at(index));
1893  symbolHandle member_sig (THREAD, cp->uncached_signature_ref_at(index));
1894  objArrayOop  dest_o = oopFactory::new_objArray(SystemDictionary::String_klass(), 3, CHECK_NULL);
1895  objArrayHandle dest(THREAD, dest_o);
1896  Handle str = java_lang_String::create_from_symbol(klass_name, CHECK_NULL);
1897  dest->obj_at_put(0, str());
1898  str = java_lang_String::create_from_symbol(member_name, CHECK_NULL);
1899  dest->obj_at_put(1, str());
1900  str = java_lang_String::create_from_symbol(member_sig, CHECK_NULL);
1901  dest->obj_at_put(2, str());
1902  return (jobjectArray) JNIHandles::make_local(dest());
1903}
1904JVM_END
1905
1906JVM_ENTRY(jint, JVM_ConstantPoolGetIntAt(JNIEnv *env, jobject unused, jobject jcpool, jint index))
1907{
1908  JVMWrapper("JVM_ConstantPoolGetIntAt");
1909  constantPoolHandle cp = constantPoolHandle(THREAD, constantPoolOop(JNIHandles::resolve_non_null(jcpool)));
1910  bounds_check(cp, index, CHECK_0);
1911  constantTag tag = cp->tag_at(index);
1912  if (!tag.is_int()) {
1913    THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
1914  }
1915  return cp->int_at(index);
1916}
1917JVM_END
1918
1919JVM_ENTRY(jlong, JVM_ConstantPoolGetLongAt(JNIEnv *env, jobject unused, jobject jcpool, jint index))
1920{
1921  JVMWrapper("JVM_ConstantPoolGetLongAt");
1922  constantPoolHandle cp = constantPoolHandle(THREAD, constantPoolOop(JNIHandles::resolve_non_null(jcpool)));
1923  bounds_check(cp, index, CHECK_(0L));
1924  constantTag tag = cp->tag_at(index);
1925  if (!tag.is_long()) {
1926    THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
1927  }
1928  return cp->long_at(index);
1929}
1930JVM_END
1931
1932JVM_ENTRY(jfloat, JVM_ConstantPoolGetFloatAt(JNIEnv *env, jobject unused, jobject jcpool, jint index))
1933{
1934  JVMWrapper("JVM_ConstantPoolGetFloatAt");
1935  constantPoolHandle cp = constantPoolHandle(THREAD, constantPoolOop(JNIHandles::resolve_non_null(jcpool)));
1936  bounds_check(cp, index, CHECK_(0.0f));
1937  constantTag tag = cp->tag_at(index);
1938  if (!tag.is_float()) {
1939    THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
1940  }
1941  return cp->float_at(index);
1942}
1943JVM_END
1944
1945JVM_ENTRY(jdouble, JVM_ConstantPoolGetDoubleAt(JNIEnv *env, jobject unused, jobject jcpool, jint index))
1946{
1947  JVMWrapper("JVM_ConstantPoolGetDoubleAt");
1948  constantPoolHandle cp = constantPoolHandle(THREAD, constantPoolOop(JNIHandles::resolve_non_null(jcpool)));
1949  bounds_check(cp, index, CHECK_(0.0));
1950  constantTag tag = cp->tag_at(index);
1951  if (!tag.is_double()) {
1952    THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
1953  }
1954  return cp->double_at(index);
1955}
1956JVM_END
1957
1958JVM_ENTRY(jstring, JVM_ConstantPoolGetStringAt(JNIEnv *env, jobject unused, jobject jcpool, jint index))
1959{
1960  JVMWrapper("JVM_ConstantPoolGetStringAt");
1961  constantPoolHandle cp = constantPoolHandle(THREAD, constantPoolOop(JNIHandles::resolve_non_null(jcpool)));
1962  bounds_check(cp, index, CHECK_NULL);
1963  constantTag tag = cp->tag_at(index);
1964  if (!tag.is_string() && !tag.is_unresolved_string()) {
1965    THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
1966  }
1967  oop str = cp->string_at(index, CHECK_NULL);
1968  return (jstring) JNIHandles::make_local(str);
1969}
1970JVM_END
1971
1972JVM_ENTRY(jstring, JVM_ConstantPoolGetUTF8At(JNIEnv *env, jobject unused, jobject jcpool, jint index))
1973{
1974  JVMWrapper("JVM_ConstantPoolGetUTF8At");
1975  JvmtiVMObjectAllocEventCollector oam;
1976  constantPoolHandle cp = constantPoolHandle(THREAD, constantPoolOop(JNIHandles::resolve_non_null(jcpool)));
1977  bounds_check(cp, index, CHECK_NULL);
1978  constantTag tag = cp->tag_at(index);
1979  if (!tag.is_symbol()) {
1980    THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
1981  }
1982  symbolOop sym_o = cp->symbol_at(index);
1983  symbolHandle sym(THREAD, sym_o);
1984  Handle str = java_lang_String::create_from_symbol(sym, CHECK_NULL);
1985  return (jstring) JNIHandles::make_local(str());
1986}
1987JVM_END
1988
1989
1990// Assertion support. //////////////////////////////////////////////////////////
1991
1992JVM_ENTRY(jboolean, JVM_DesiredAssertionStatus(JNIEnv *env, jclass unused, jclass cls))
1993  JVMWrapper("JVM_DesiredAssertionStatus");
1994  assert(cls != NULL, "bad class");
1995
1996  oop r = JNIHandles::resolve(cls);
1997  assert(! java_lang_Class::is_primitive(r), "primitive classes not allowed");
1998  if (java_lang_Class::is_primitive(r)) return false;
1999
2000  klassOop k = java_lang_Class::as_klassOop(r);
2001  assert(Klass::cast(k)->oop_is_instance(), "must be an instance klass");
2002  if (! Klass::cast(k)->oop_is_instance()) return false;
2003
2004  ResourceMark rm(THREAD);
2005  const char* name = Klass::cast(k)->name()->as_C_string();
2006  bool system_class = Klass::cast(k)->class_loader() == NULL;
2007  return JavaAssertions::enabled(name, system_class);
2008
2009JVM_END
2010
2011
2012// Return a new AssertionStatusDirectives object with the fields filled in with
2013// command-line assertion arguments (i.e., -ea, -da).
2014JVM_ENTRY(jobject, JVM_AssertionStatusDirectives(JNIEnv *env, jclass unused))
2015  JVMWrapper("JVM_AssertionStatusDirectives");
2016  JvmtiVMObjectAllocEventCollector oam;
2017  oop asd = JavaAssertions::createAssertionStatusDirectives(CHECK_NULL);
2018  return JNIHandles::make_local(env, asd);
2019JVM_END
2020
2021// Verification ////////////////////////////////////////////////////////////////////////////////
2022
2023// Reflection for the verifier /////////////////////////////////////////////////////////////////
2024
2025// RedefineClasses support: bug 6214132 caused verification to fail.
2026// All functions from this section should call the jvmtiThreadSate function:
2027//   klassOop class_to_verify_considering_redefinition(klassOop klass).
2028// The function returns a klassOop of the _scratch_class if the verifier
2029// was invoked in the middle of the class redefinition.
2030// Otherwise it returns its argument value which is the _the_class klassOop.
2031// Please, refer to the description in the jvmtiThreadSate.hpp.
2032
2033JVM_ENTRY(const char*, JVM_GetClassNameUTF(JNIEnv *env, jclass cls))
2034  JVMWrapper("JVM_GetClassNameUTF");
2035  klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls));
2036  k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2037  return Klass::cast(k)->name()->as_utf8();
2038JVM_END
2039
2040
2041JVM_QUICK_ENTRY(void, JVM_GetClassCPTypes(JNIEnv *env, jclass cls, unsigned char *types))
2042  JVMWrapper("JVM_GetClassCPTypes");
2043  klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls));
2044  k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2045  // types will have length zero if this is not an instanceKlass
2046  // (length is determined by call to JVM_GetClassCPEntriesCount)
2047  if (Klass::cast(k)->oop_is_instance()) {
2048    constantPoolOop cp = instanceKlass::cast(k)->constants();
2049    for (int index = cp->length() - 1; index >= 0; index--) {
2050      constantTag tag = cp->tag_at(index);
2051      types[index] = (tag.is_unresolved_klass()) ? JVM_CONSTANT_Class :
2052                     (tag.is_unresolved_string()) ? JVM_CONSTANT_String : tag.value();
2053  }
2054  }
2055JVM_END
2056
2057
2058JVM_QUICK_ENTRY(jint, JVM_GetClassCPEntriesCount(JNIEnv *env, jclass cls))
2059  JVMWrapper("JVM_GetClassCPEntriesCount");
2060  klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls));
2061  k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2062  if (!Klass::cast(k)->oop_is_instance())
2063    return 0;
2064  return instanceKlass::cast(k)->constants()->length();
2065JVM_END
2066
2067
2068JVM_QUICK_ENTRY(jint, JVM_GetClassFieldsCount(JNIEnv *env, jclass cls))
2069  JVMWrapper("JVM_GetClassFieldsCount");
2070  klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls));
2071  k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2072  if (!Klass::cast(k)->oop_is_instance())
2073    return 0;
2074  return instanceKlass::cast(k)->fields()->length() / instanceKlass::next_offset;
2075JVM_END
2076
2077
2078JVM_QUICK_ENTRY(jint, JVM_GetClassMethodsCount(JNIEnv *env, jclass cls))
2079  JVMWrapper("JVM_GetClassMethodsCount");
2080  klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls));
2081  k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2082  if (!Klass::cast(k)->oop_is_instance())
2083    return 0;
2084  return instanceKlass::cast(k)->methods()->length();
2085JVM_END
2086
2087
2088// The following methods, used for the verifier, are never called with
2089// array klasses, so a direct cast to instanceKlass is safe.
2090// Typically, these methods are called in a loop with bounds determined
2091// by the results of JVM_GetClass{Fields,Methods}Count, which return
2092// zero for arrays.
2093JVM_QUICK_ENTRY(void, JVM_GetMethodIxExceptionIndexes(JNIEnv *env, jclass cls, jint method_index, unsigned short *exceptions))
2094  JVMWrapper("JVM_GetMethodIxExceptionIndexes");
2095  klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls));
2096  k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2097  oop method = instanceKlass::cast(k)->methods()->obj_at(method_index);
2098  int length = methodOop(method)->checked_exceptions_length();
2099  if (length > 0) {
2100    CheckedExceptionElement* table= methodOop(method)->checked_exceptions_start();
2101    for (int i = 0; i < length; i++) {
2102      exceptions[i] = table[i].class_cp_index;
2103    }
2104  }
2105JVM_END
2106
2107
2108JVM_QUICK_ENTRY(jint, JVM_GetMethodIxExceptionsCount(JNIEnv *env, jclass cls, jint method_index))
2109  JVMWrapper("JVM_GetMethodIxExceptionsCount");
2110  klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls));
2111  k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2112  oop method = instanceKlass::cast(k)->methods()->obj_at(method_index);
2113  return methodOop(method)->checked_exceptions_length();
2114JVM_END
2115
2116
2117JVM_QUICK_ENTRY(void, JVM_GetMethodIxByteCode(JNIEnv *env, jclass cls, jint method_index, unsigned char *code))
2118  JVMWrapper("JVM_GetMethodIxByteCode");
2119  klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls));
2120  k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2121  oop method = instanceKlass::cast(k)->methods()->obj_at(method_index);
2122  memcpy(code, methodOop(method)->code_base(), methodOop(method)->code_size());
2123JVM_END
2124
2125
2126JVM_QUICK_ENTRY(jint, JVM_GetMethodIxByteCodeLength(JNIEnv *env, jclass cls, jint method_index))
2127  JVMWrapper("JVM_GetMethodIxByteCodeLength");
2128  klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls));
2129  k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2130  oop method = instanceKlass::cast(k)->methods()->obj_at(method_index);
2131  return methodOop(method)->code_size();
2132JVM_END
2133
2134
2135JVM_QUICK_ENTRY(void, JVM_GetMethodIxExceptionTableEntry(JNIEnv *env, jclass cls, jint method_index, jint entry_index, JVM_ExceptionTableEntryType *entry))
2136  JVMWrapper("JVM_GetMethodIxExceptionTableEntry");
2137  klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls));
2138  k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2139  oop method = instanceKlass::cast(k)->methods()->obj_at(method_index);
2140  typeArrayOop extable = methodOop(method)->exception_table();
2141  entry->start_pc   = extable->int_at(entry_index * 4);
2142  entry->end_pc     = extable->int_at(entry_index * 4 + 1);
2143  entry->handler_pc = extable->int_at(entry_index * 4 + 2);
2144  entry->catchType  = extable->int_at(entry_index * 4 + 3);
2145JVM_END
2146
2147
2148JVM_QUICK_ENTRY(jint, JVM_GetMethodIxExceptionTableLength(JNIEnv *env, jclass cls, int method_index))
2149  JVMWrapper("JVM_GetMethodIxExceptionTableLength");
2150  klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls));
2151  k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2152  oop method = instanceKlass::cast(k)->methods()->obj_at(method_index);
2153  return methodOop(method)->exception_table()->length() / 4;
2154JVM_END
2155
2156
2157JVM_QUICK_ENTRY(jint, JVM_GetMethodIxModifiers(JNIEnv *env, jclass cls, int method_index))
2158  JVMWrapper("JVM_GetMethodIxModifiers");
2159  klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls));
2160  k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2161  oop method = instanceKlass::cast(k)->methods()->obj_at(method_index);
2162  return methodOop(method)->access_flags().as_int() & JVM_RECOGNIZED_METHOD_MODIFIERS;
2163JVM_END
2164
2165
2166JVM_QUICK_ENTRY(jint, JVM_GetFieldIxModifiers(JNIEnv *env, jclass cls, int field_index))
2167  JVMWrapper("JVM_GetFieldIxModifiers");
2168  klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls));
2169  k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2170  typeArrayOop fields = instanceKlass::cast(k)->fields();
2171  return fields->ushort_at(field_index * instanceKlass::next_offset + instanceKlass::access_flags_offset) & JVM_RECOGNIZED_FIELD_MODIFIERS;
2172JVM_END
2173
2174
2175JVM_QUICK_ENTRY(jint, JVM_GetMethodIxLocalsCount(JNIEnv *env, jclass cls, int method_index))
2176  JVMWrapper("JVM_GetMethodIxLocalsCount");
2177  klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls));
2178  k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2179  oop method = instanceKlass::cast(k)->methods()->obj_at(method_index);
2180  return methodOop(method)->max_locals();
2181JVM_END
2182
2183
2184JVM_QUICK_ENTRY(jint, JVM_GetMethodIxArgsSize(JNIEnv *env, jclass cls, int method_index))
2185  JVMWrapper("JVM_GetMethodIxArgsSize");
2186  klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls));
2187  k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2188  oop method = instanceKlass::cast(k)->methods()->obj_at(method_index);
2189  return methodOop(method)->size_of_parameters();
2190JVM_END
2191
2192
2193JVM_QUICK_ENTRY(jint, JVM_GetMethodIxMaxStack(JNIEnv *env, jclass cls, int method_index))
2194  JVMWrapper("JVM_GetMethodIxMaxStack");
2195  klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls));
2196  k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2197  oop method = instanceKlass::cast(k)->methods()->obj_at(method_index);
2198  return methodOop(method)->max_stack();
2199JVM_END
2200
2201
2202JVM_QUICK_ENTRY(jboolean, JVM_IsConstructorIx(JNIEnv *env, jclass cls, int method_index))
2203  JVMWrapper("JVM_IsConstructorIx");
2204  ResourceMark rm(THREAD);
2205  klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls));
2206  k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2207  oop method = instanceKlass::cast(k)->methods()->obj_at(method_index);
2208  return methodOop(method)->name() == vmSymbols::object_initializer_name();
2209JVM_END
2210
2211
2212JVM_ENTRY(const char*, JVM_GetMethodIxNameUTF(JNIEnv *env, jclass cls, jint method_index))
2213  JVMWrapper("JVM_GetMethodIxIxUTF");
2214  klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls));
2215  k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2216  oop method = instanceKlass::cast(k)->methods()->obj_at(method_index);
2217  return methodOop(method)->name()->as_utf8();
2218JVM_END
2219
2220
2221JVM_ENTRY(const char*, JVM_GetMethodIxSignatureUTF(JNIEnv *env, jclass cls, jint method_index))
2222  JVMWrapper("JVM_GetMethodIxSignatureUTF");
2223  klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls));
2224  k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2225  oop method = instanceKlass::cast(k)->methods()->obj_at(method_index);
2226  return methodOop(method)->signature()->as_utf8();
2227JVM_END
2228
2229/**
2230 * All of these JVM_GetCP-xxx methods are used by the old verifier to
2231 * read entries in the constant pool.  Since the old verifier always
2232 * works on a copy of the code, it will not see any rewriting that
2233 * may possibly occur in the middle of verification.  So it is important
2234 * that nothing it calls tries to use the cpCache instead of the raw
2235 * constant pool, so we must use cp->uncached_x methods when appropriate.
2236 */
2237JVM_ENTRY(const char*, JVM_GetCPFieldNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2238  JVMWrapper("JVM_GetCPFieldNameUTF");
2239  klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls));
2240  k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2241  constantPoolOop cp = instanceKlass::cast(k)->constants();
2242  switch (cp->tag_at(cp_index).value()) {
2243    case JVM_CONSTANT_Fieldref:
2244      return cp->uncached_name_ref_at(cp_index)->as_utf8();
2245    default:
2246      fatal("JVM_GetCPFieldNameUTF: illegal constant");
2247  }
2248  ShouldNotReachHere();
2249  return NULL;
2250JVM_END
2251
2252
2253JVM_ENTRY(const char*, JVM_GetCPMethodNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2254  JVMWrapper("JVM_GetCPMethodNameUTF");
2255  klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls));
2256  k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2257  constantPoolOop cp = instanceKlass::cast(k)->constants();
2258  switch (cp->tag_at(cp_index).value()) {
2259    case JVM_CONSTANT_InterfaceMethodref:
2260    case JVM_CONSTANT_Methodref:
2261    case JVM_CONSTANT_NameAndType:  // for invokedynamic
2262      return cp->uncached_name_ref_at(cp_index)->as_utf8();
2263    default:
2264      fatal("JVM_GetCPMethodNameUTF: illegal constant");
2265  }
2266  ShouldNotReachHere();
2267  return NULL;
2268JVM_END
2269
2270
2271JVM_ENTRY(const char*, JVM_GetCPMethodSignatureUTF(JNIEnv *env, jclass cls, jint cp_index))
2272  JVMWrapper("JVM_GetCPMethodSignatureUTF");
2273  klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls));
2274  k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2275  constantPoolOop cp = instanceKlass::cast(k)->constants();
2276  switch (cp->tag_at(cp_index).value()) {
2277    case JVM_CONSTANT_InterfaceMethodref:
2278    case JVM_CONSTANT_Methodref:
2279    case JVM_CONSTANT_NameAndType:  // for invokedynamic
2280      return cp->uncached_signature_ref_at(cp_index)->as_utf8();
2281    default:
2282      fatal("JVM_GetCPMethodSignatureUTF: illegal constant");
2283  }
2284  ShouldNotReachHere();
2285  return NULL;
2286JVM_END
2287
2288
2289JVM_ENTRY(const char*, JVM_GetCPFieldSignatureUTF(JNIEnv *env, jclass cls, jint cp_index))
2290  JVMWrapper("JVM_GetCPFieldSignatureUTF");
2291  klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls));
2292  k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2293  constantPoolOop cp = instanceKlass::cast(k)->constants();
2294  switch (cp->tag_at(cp_index).value()) {
2295    case JVM_CONSTANT_Fieldref:
2296      return cp->uncached_signature_ref_at(cp_index)->as_utf8();
2297    default:
2298      fatal("JVM_GetCPFieldSignatureUTF: illegal constant");
2299  }
2300  ShouldNotReachHere();
2301  return NULL;
2302JVM_END
2303
2304
2305JVM_ENTRY(const char*, JVM_GetCPClassNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2306  JVMWrapper("JVM_GetCPClassNameUTF");
2307  klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls));
2308  k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2309  constantPoolOop cp = instanceKlass::cast(k)->constants();
2310  symbolOop classname = cp->klass_name_at(cp_index);
2311  return classname->as_utf8();
2312JVM_END
2313
2314
2315JVM_ENTRY(const char*, JVM_GetCPFieldClassNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2316  JVMWrapper("JVM_GetCPFieldClassNameUTF");
2317  klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls));
2318  k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2319  constantPoolOop cp = instanceKlass::cast(k)->constants();
2320  switch (cp->tag_at(cp_index).value()) {
2321    case JVM_CONSTANT_Fieldref: {
2322      int class_index = cp->uncached_klass_ref_index_at(cp_index);
2323      symbolOop classname = cp->klass_name_at(class_index);
2324      return classname->as_utf8();
2325    }
2326    default:
2327      fatal("JVM_GetCPFieldClassNameUTF: illegal constant");
2328  }
2329  ShouldNotReachHere();
2330  return NULL;
2331JVM_END
2332
2333
2334JVM_ENTRY(const char*, JVM_GetCPMethodClassNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2335  JVMWrapper("JVM_GetCPMethodClassNameUTF");
2336  klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls));
2337  k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2338  constantPoolOop cp = instanceKlass::cast(k)->constants();
2339  switch (cp->tag_at(cp_index).value()) {
2340    case JVM_CONSTANT_Methodref:
2341    case JVM_CONSTANT_InterfaceMethodref: {
2342      int class_index = cp->uncached_klass_ref_index_at(cp_index);
2343      symbolOop classname = cp->klass_name_at(class_index);
2344      return classname->as_utf8();
2345    }
2346    default:
2347      fatal("JVM_GetCPMethodClassNameUTF: illegal constant");
2348  }
2349  ShouldNotReachHere();
2350  return NULL;
2351JVM_END
2352
2353
2354JVM_QUICK_ENTRY(jint, JVM_GetCPFieldModifiers(JNIEnv *env, jclass cls, int cp_index, jclass called_cls))
2355  JVMWrapper("JVM_GetCPFieldModifiers");
2356  klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls));
2357  klassOop k_called = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(called_cls));
2358  k        = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2359  k_called = JvmtiThreadState::class_to_verify_considering_redefinition(k_called, thread);
2360  constantPoolOop cp = instanceKlass::cast(k)->constants();
2361  constantPoolOop cp_called = instanceKlass::cast(k_called)->constants();
2362  switch (cp->tag_at(cp_index).value()) {
2363    case JVM_CONSTANT_Fieldref: {
2364      symbolOop name      = cp->uncached_name_ref_at(cp_index);
2365      symbolOop signature = cp->uncached_signature_ref_at(cp_index);
2366      typeArrayOop fields = instanceKlass::cast(k_called)->fields();
2367      int fields_count = fields->length();
2368      for (int i = 0; i < fields_count; i += instanceKlass::next_offset) {
2369        if (cp_called->symbol_at(fields->ushort_at(i + instanceKlass::name_index_offset)) == name &&
2370            cp_called->symbol_at(fields->ushort_at(i + instanceKlass::signature_index_offset)) == signature) {
2371          return fields->ushort_at(i + instanceKlass::access_flags_offset) & JVM_RECOGNIZED_FIELD_MODIFIERS;
2372        }
2373      }
2374      return -1;
2375    }
2376    default:
2377      fatal("JVM_GetCPFieldModifiers: illegal constant");
2378  }
2379  ShouldNotReachHere();
2380  return 0;
2381JVM_END
2382
2383
2384JVM_QUICK_ENTRY(jint, JVM_GetCPMethodModifiers(JNIEnv *env, jclass cls, int cp_index, jclass called_cls))
2385  JVMWrapper("JVM_GetCPMethodModifiers");
2386  klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls));
2387  klassOop k_called = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(called_cls));
2388  k        = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2389  k_called = JvmtiThreadState::class_to_verify_considering_redefinition(k_called, thread);
2390  constantPoolOop cp = instanceKlass::cast(k)->constants();
2391  switch (cp->tag_at(cp_index).value()) {
2392    case JVM_CONSTANT_Methodref:
2393    case JVM_CONSTANT_InterfaceMethodref: {
2394      symbolOop name      = cp->uncached_name_ref_at(cp_index);
2395      symbolOop signature = cp->uncached_signature_ref_at(cp_index);
2396      objArrayOop methods = instanceKlass::cast(k_called)->methods();
2397      int methods_count = methods->length();
2398      for (int i = 0; i < methods_count; i++) {
2399        methodOop method = methodOop(methods->obj_at(i));
2400        if (method->name() == name && method->signature() == signature) {
2401            return method->access_flags().as_int() & JVM_RECOGNIZED_METHOD_MODIFIERS;
2402        }
2403      }
2404      return -1;
2405    }
2406    default:
2407      fatal("JVM_GetCPMethodModifiers: illegal constant");
2408  }
2409  ShouldNotReachHere();
2410  return 0;
2411JVM_END
2412
2413
2414// Misc //////////////////////////////////////////////////////////////////////////////////////////////
2415
2416JVM_LEAF(void, JVM_ReleaseUTF(const char *utf))
2417  // So long as UTF8::convert_to_utf8 returns resource strings, we don't have to do anything
2418JVM_END
2419
2420
2421JVM_ENTRY(jboolean, JVM_IsSameClassPackage(JNIEnv *env, jclass class1, jclass class2))
2422  JVMWrapper("JVM_IsSameClassPackage");
2423  oop class1_mirror = JNIHandles::resolve_non_null(class1);
2424  oop class2_mirror = JNIHandles::resolve_non_null(class2);
2425  klassOop klass1 = java_lang_Class::as_klassOop(class1_mirror);
2426  klassOop klass2 = java_lang_Class::as_klassOop(class2_mirror);
2427  return (jboolean) Reflection::is_same_class_package(klass1, klass2);
2428JVM_END
2429
2430
2431// IO functions ////////////////////////////////////////////////////////////////////////////////////////
2432
2433JVM_LEAF(jint, JVM_Open(const char *fname, jint flags, jint mode))
2434  JVMWrapper2("JVM_Open (%s)", fname);
2435
2436  //%note jvm_r6
2437  int result = hpi::open(fname, flags, mode);
2438  if (result >= 0) {
2439    return result;
2440  } else {
2441    switch(errno) {
2442      case EEXIST:
2443        return JVM_EEXIST;
2444      default:
2445        return -1;
2446    }
2447  }
2448JVM_END
2449
2450
2451JVM_LEAF(jint, JVM_Close(jint fd))
2452  JVMWrapper2("JVM_Close (0x%x)", fd);
2453  //%note jvm_r6
2454  return hpi::close(fd);
2455JVM_END
2456
2457
2458JVM_LEAF(jint, JVM_Read(jint fd, char *buf, jint nbytes))
2459  JVMWrapper2("JVM_Read (0x%x)", fd);
2460
2461  //%note jvm_r6
2462  return (jint)hpi::read(fd, buf, nbytes);
2463JVM_END
2464
2465
2466JVM_LEAF(jint, JVM_Write(jint fd, char *buf, jint nbytes))
2467  JVMWrapper2("JVM_Write (0x%x)", fd);
2468
2469  //%note jvm_r6
2470  return (jint)hpi::write(fd, buf, nbytes);
2471JVM_END
2472
2473
2474JVM_LEAF(jint, JVM_Available(jint fd, jlong *pbytes))
2475  JVMWrapper2("JVM_Available (0x%x)", fd);
2476  //%note jvm_r6
2477  return hpi::available(fd, pbytes);
2478JVM_END
2479
2480
2481JVM_LEAF(jlong, JVM_Lseek(jint fd, jlong offset, jint whence))
2482  JVMWrapper4("JVM_Lseek (0x%x, %Ld, %d)", fd, offset, whence);
2483  //%note jvm_r6
2484  return hpi::lseek(fd, offset, whence);
2485JVM_END
2486
2487
2488JVM_LEAF(jint, JVM_SetLength(jint fd, jlong length))
2489  JVMWrapper3("JVM_SetLength (0x%x, %Ld)", fd, length);
2490  return hpi::ftruncate(fd, length);
2491JVM_END
2492
2493
2494JVM_LEAF(jint, JVM_Sync(jint fd))
2495  JVMWrapper2("JVM_Sync (0x%x)", fd);
2496  //%note jvm_r6
2497  return hpi::fsync(fd);
2498JVM_END
2499
2500
2501// Printing support //////////////////////////////////////////////////
2502extern "C" {
2503
2504int jio_vsnprintf(char *str, size_t count, const char *fmt, va_list args) {
2505  // see bug 4399518, 4417214
2506  if ((intptr_t)count <= 0) return -1;
2507  return vsnprintf(str, count, fmt, args);
2508}
2509
2510
2511int jio_snprintf(char *str, size_t count, const char *fmt, ...) {
2512  va_list args;
2513  int len;
2514  va_start(args, fmt);
2515  len = jio_vsnprintf(str, count, fmt, args);
2516  va_end(args);
2517  return len;
2518}
2519
2520
2521int jio_fprintf(FILE* f, const char *fmt, ...) {
2522  int len;
2523  va_list args;
2524  va_start(args, fmt);
2525  len = jio_vfprintf(f, fmt, args);
2526  va_end(args);
2527  return len;
2528}
2529
2530
2531int jio_vfprintf(FILE* f, const char *fmt, va_list args) {
2532  if (Arguments::vfprintf_hook() != NULL) {
2533     return Arguments::vfprintf_hook()(f, fmt, args);
2534  } else {
2535    return vfprintf(f, fmt, args);
2536  }
2537}
2538
2539
2540int jio_printf(const char *fmt, ...) {
2541  int len;
2542  va_list args;
2543  va_start(args, fmt);
2544  len = jio_vfprintf(defaultStream::output_stream(), fmt, args);
2545  va_end(args);
2546  return len;
2547}
2548
2549
2550// HotSpot specific jio method
2551void jio_print(const char* s) {
2552  // Try to make this function as atomic as possible.
2553  if (Arguments::vfprintf_hook() != NULL) {
2554    jio_fprintf(defaultStream::output_stream(), "%s", s);
2555  } else {
2556    // Make an unused local variable to avoid warning from gcc 4.x compiler.
2557    size_t count = ::write(defaultStream::output_fd(), s, (int)strlen(s));
2558  }
2559}
2560
2561} // Extern C
2562
2563// java.lang.Thread //////////////////////////////////////////////////////////////////////////////
2564
2565// In most of the JVM Thread support functions we need to be sure to lock the Threads_lock
2566// to prevent the target thread from exiting after we have a pointer to the C++ Thread or
2567// OSThread objects.  The exception to this rule is when the target object is the thread
2568// doing the operation, in which case we know that the thread won't exit until the
2569// operation is done (all exits being voluntary).  There are a few cases where it is
2570// rather silly to do operations on yourself, like resuming yourself or asking whether
2571// you are alive.  While these can still happen, they are not subject to deadlocks if
2572// the lock is held while the operation occurs (this is not the case for suspend, for
2573// instance), and are very unlikely.  Because IsAlive needs to be fast and its
2574// implementation is local to this file, we always lock Threads_lock for that one.
2575
2576static void thread_entry(JavaThread* thread, TRAPS) {
2577  HandleMark hm(THREAD);
2578  Handle obj(THREAD, thread->threadObj());
2579  JavaValue result(T_VOID);
2580  JavaCalls::call_virtual(&result,
2581                          obj,
2582                          KlassHandle(THREAD, SystemDictionary::Thread_klass()),
2583                          vmSymbolHandles::run_method_name(),
2584                          vmSymbolHandles::void_method_signature(),
2585                          THREAD);
2586}
2587
2588
2589JVM_ENTRY(void, JVM_StartThread(JNIEnv* env, jobject jthread))
2590  JVMWrapper("JVM_StartThread");
2591  JavaThread *native_thread = NULL;
2592
2593  // We cannot hold the Threads_lock when we throw an exception,
2594  // due to rank ordering issues. Example:  we might need to grab the
2595  // Heap_lock while we construct the exception.
2596  bool throw_illegal_thread_state = false;
2597
2598  // We must release the Threads_lock before we can post a jvmti event
2599  // in Thread::start.
2600  {
2601    // Ensure that the C++ Thread and OSThread structures aren't freed before
2602    // we operate.
2603    MutexLocker mu(Threads_lock);
2604
2605    // Check to see if we're running a thread that's already exited or was
2606    // stopped (is_stillborn) or is still active (thread is not NULL).
2607    if (java_lang_Thread::is_stillborn(JNIHandles::resolve_non_null(jthread)) ||
2608        java_lang_Thread::thread(JNIHandles::resolve_non_null(jthread)) != NULL) {
2609        throw_illegal_thread_state = true;
2610    } else {
2611      jlong size =
2612             java_lang_Thread::stackSize(JNIHandles::resolve_non_null(jthread));
2613      // Allocate the C++ Thread structure and create the native thread.  The
2614      // stack size retrieved from java is signed, but the constructor takes
2615      // size_t (an unsigned type), so avoid passing negative values which would
2616      // result in really large stacks.
2617      size_t sz = size > 0 ? (size_t) size : 0;
2618      native_thread = new JavaThread(&thread_entry, sz);
2619
2620      // At this point it may be possible that no osthread was created for the
2621      // JavaThread due to lack of memory. Check for this situation and throw
2622      // an exception if necessary. Eventually we may want to change this so
2623      // that we only grab the lock if the thread was created successfully -
2624      // then we can also do this check and throw the exception in the
2625      // JavaThread constructor.
2626      if (native_thread->osthread() != NULL) {
2627        // Note: the current thread is not being used within "prepare".
2628        native_thread->prepare(jthread);
2629      }
2630    }
2631  }
2632
2633  if (throw_illegal_thread_state) {
2634    THROW(vmSymbols::java_lang_IllegalThreadStateException());
2635  }
2636
2637  assert(native_thread != NULL, "Starting null thread?");
2638
2639  if (native_thread->osthread() == NULL) {
2640    // No one should hold a reference to the 'native_thread'.
2641    delete native_thread;
2642    if (JvmtiExport::should_post_resource_exhausted()) {
2643      JvmtiExport::post_resource_exhausted(
2644        JVMTI_RESOURCE_EXHAUSTED_OOM_ERROR | JVMTI_RESOURCE_EXHAUSTED_THREADS,
2645        "unable to create new native thread");
2646    }
2647    THROW_MSG(vmSymbols::java_lang_OutOfMemoryError(),
2648              "unable to create new native thread");
2649  }
2650
2651  Thread::start(native_thread);
2652
2653JVM_END
2654
2655// JVM_Stop is implemented using a VM_Operation, so threads are forced to safepoints
2656// before the quasi-asynchronous exception is delivered.  This is a little obtrusive,
2657// but is thought to be reliable and simple. In the case, where the receiver is the
2658// save thread as the sender, no safepoint is needed.
2659JVM_ENTRY(void, JVM_StopThread(JNIEnv* env, jobject jthread, jobject throwable))
2660  JVMWrapper("JVM_StopThread");
2661
2662  oop java_throwable = JNIHandles::resolve(throwable);
2663  if (java_throwable == NULL) {
2664    THROW(vmSymbols::java_lang_NullPointerException());
2665  }
2666  oop java_thread = JNIHandles::resolve_non_null(jthread);
2667  JavaThread* receiver = java_lang_Thread::thread(java_thread);
2668  Events::log("JVM_StopThread thread JavaThread " INTPTR_FORMAT " as oop " INTPTR_FORMAT " [exception " INTPTR_FORMAT "]", receiver, (address)java_thread, throwable);
2669  // First check if thread already exited
2670  if (receiver != NULL) {
2671    // Check if exception is getting thrown at self (use oop equality, since the
2672    // target object might exit)
2673    if (java_thread == thread->threadObj()) {
2674      // This is a change from JDK 1.1, but JDK 1.2 will also do it:
2675      // NOTE (from JDK 1.2): this is done solely to prevent stopped
2676      // threads from being restarted.
2677      // Fix for 4314342, 4145910, perhaps others: it now doesn't have
2678      // any effect on the "liveness" of a thread; see
2679      // JVM_IsThreadAlive, below.
2680      if (java_throwable->is_a(SystemDictionary::ThreadDeath_klass())) {
2681        java_lang_Thread::set_stillborn(java_thread);
2682      }
2683      THROW_OOP(java_throwable);
2684    } else {
2685      // Enques a VM_Operation to stop all threads and then deliver the exception...
2686      Thread::send_async_exception(java_thread, JNIHandles::resolve(throwable));
2687    }
2688  }
2689JVM_END
2690
2691
2692JVM_ENTRY(jboolean, JVM_IsThreadAlive(JNIEnv* env, jobject jthread))
2693  JVMWrapper("JVM_IsThreadAlive");
2694
2695  oop thread_oop = JNIHandles::resolve_non_null(jthread);
2696  return java_lang_Thread::is_alive(thread_oop);
2697JVM_END
2698
2699
2700JVM_ENTRY(void, JVM_SuspendThread(JNIEnv* env, jobject jthread))
2701  JVMWrapper("JVM_SuspendThread");
2702  oop java_thread = JNIHandles::resolve_non_null(jthread);
2703  JavaThread* receiver = java_lang_Thread::thread(java_thread);
2704
2705  if (receiver != NULL) {
2706    // thread has run and has not exited (still on threads list)
2707
2708    {
2709      MutexLockerEx ml(receiver->SR_lock(), Mutex::_no_safepoint_check_flag);
2710      if (receiver->is_external_suspend()) {
2711        // Don't allow nested external suspend requests. We can't return
2712        // an error from this interface so just ignore the problem.
2713        return;
2714      }
2715      if (receiver->is_exiting()) { // thread is in the process of exiting
2716        return;
2717      }
2718      receiver->set_external_suspend();
2719    }
2720
2721    // java_suspend() will catch threads in the process of exiting
2722    // and will ignore them.
2723    receiver->java_suspend();
2724
2725    // It would be nice to have the following assertion in all the
2726    // time, but it is possible for a racing resume request to have
2727    // resumed this thread right after we suspended it. Temporarily
2728    // enable this assertion if you are chasing a different kind of
2729    // bug.
2730    //
2731    // assert(java_lang_Thread::thread(receiver->threadObj()) == NULL ||
2732    //   receiver->is_being_ext_suspended(), "thread is not suspended");
2733  }
2734JVM_END
2735
2736
2737JVM_ENTRY(void, JVM_ResumeThread(JNIEnv* env, jobject jthread))
2738  JVMWrapper("JVM_ResumeThread");
2739  // Ensure that the C++ Thread and OSThread structures aren't freed before we operate.
2740  // We need to *always* get the threads lock here, since this operation cannot be allowed during
2741  // a safepoint. The safepoint code relies on suspending a thread to examine its state. If other
2742  // threads randomly resumes threads, then a thread might not be suspended when the safepoint code
2743  // looks at it.
2744  MutexLocker ml(Threads_lock);
2745  JavaThread* thr = java_lang_Thread::thread(JNIHandles::resolve_non_null(jthread));
2746  if (thr != NULL) {
2747    // the thread has run and is not in the process of exiting
2748    thr->java_resume();
2749  }
2750JVM_END
2751
2752
2753JVM_ENTRY(void, JVM_SetThreadPriority(JNIEnv* env, jobject jthread, jint prio))
2754  JVMWrapper("JVM_SetThreadPriority");
2755  // Ensure that the C++ Thread and OSThread structures aren't freed before we operate
2756  MutexLocker ml(Threads_lock);
2757  oop java_thread = JNIHandles::resolve_non_null(jthread);
2758  java_lang_Thread::set_priority(java_thread, (ThreadPriority)prio);
2759  JavaThread* thr = java_lang_Thread::thread(java_thread);
2760  if (thr != NULL) {                  // Thread not yet started; priority pushed down when it is
2761    Thread::set_priority(thr, (ThreadPriority)prio);
2762  }
2763JVM_END
2764
2765
2766JVM_ENTRY(void, JVM_Yield(JNIEnv *env, jclass threadClass))
2767  JVMWrapper("JVM_Yield");
2768  if (os::dont_yield()) return;
2769  HS_DTRACE_PROBE0(hotspot, thread__yield);
2770  // When ConvertYieldToSleep is off (default), this matches the classic VM use of yield.
2771  // Critical for similar threading behaviour
2772  if (ConvertYieldToSleep) {
2773    os::sleep(thread, MinSleepInterval, false);
2774  } else {
2775    os::yield();
2776  }
2777JVM_END
2778
2779
2780JVM_ENTRY(void, JVM_Sleep(JNIEnv* env, jclass threadClass, jlong millis))
2781  JVMWrapper("JVM_Sleep");
2782
2783  if (millis < 0) {
2784    THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "timeout value is negative");
2785  }
2786
2787  if (Thread::is_interrupted (THREAD, true) && !HAS_PENDING_EXCEPTION) {
2788    THROW_MSG(vmSymbols::java_lang_InterruptedException(), "sleep interrupted");
2789  }
2790
2791  // Save current thread state and restore it at the end of this block.
2792  // And set new thread state to SLEEPING.
2793  JavaThreadSleepState jtss(thread);
2794
2795  HS_DTRACE_PROBE1(hotspot, thread__sleep__begin, millis);
2796
2797  if (millis == 0) {
2798    // When ConvertSleepToYield is on, this matches the classic VM implementation of
2799    // JVM_Sleep. Critical for similar threading behaviour (Win32)
2800    // It appears that in certain GUI contexts, it may be beneficial to do a short sleep
2801    // for SOLARIS
2802    if (ConvertSleepToYield) {
2803      os::yield();
2804    } else {
2805      ThreadState old_state = thread->osthread()->get_state();
2806      thread->osthread()->set_state(SLEEPING);
2807      os::sleep(thread, MinSleepInterval, false);
2808      thread->osthread()->set_state(old_state);
2809    }
2810  } else {
2811    ThreadState old_state = thread->osthread()->get_state();
2812    thread->osthread()->set_state(SLEEPING);
2813    if (os::sleep(thread, millis, true) == OS_INTRPT) {
2814      // An asynchronous exception (e.g., ThreadDeathException) could have been thrown on
2815      // us while we were sleeping. We do not overwrite those.
2816      if (!HAS_PENDING_EXCEPTION) {
2817        HS_DTRACE_PROBE1(hotspot, thread__sleep__end,1);
2818        // TODO-FIXME: THROW_MSG returns which means we will not call set_state()
2819        // to properly restore the thread state.  That's likely wrong.
2820        THROW_MSG(vmSymbols::java_lang_InterruptedException(), "sleep interrupted");
2821      }
2822    }
2823    thread->osthread()->set_state(old_state);
2824  }
2825  HS_DTRACE_PROBE1(hotspot, thread__sleep__end,0);
2826JVM_END
2827
2828JVM_ENTRY(jobject, JVM_CurrentThread(JNIEnv* env, jclass threadClass))
2829  JVMWrapper("JVM_CurrentThread");
2830  oop jthread = thread->threadObj();
2831  assert (thread != NULL, "no current thread!");
2832  return JNIHandles::make_local(env, jthread);
2833JVM_END
2834
2835
2836JVM_ENTRY(jint, JVM_CountStackFrames(JNIEnv* env, jobject jthread))
2837  JVMWrapper("JVM_CountStackFrames");
2838
2839  // Ensure that the C++ Thread and OSThread structures aren't freed before we operate
2840  oop java_thread = JNIHandles::resolve_non_null(jthread);
2841  bool throw_illegal_thread_state = false;
2842  int count = 0;
2843
2844  {
2845    MutexLockerEx ml(thread->threadObj() == java_thread ? NULL : Threads_lock);
2846    // We need to re-resolve the java_thread, since a GC might have happened during the
2847    // acquire of the lock
2848    JavaThread* thr = java_lang_Thread::thread(JNIHandles::resolve_non_null(jthread));
2849
2850    if (thr == NULL) {
2851      // do nothing
2852    } else if(! thr->is_external_suspend() || ! thr->frame_anchor()->walkable()) {
2853      // Check whether this java thread has been suspended already. If not, throws
2854      // IllegalThreadStateException. We defer to throw that exception until
2855      // Threads_lock is released since loading exception class has to leave VM.
2856      // The correct way to test a thread is actually suspended is
2857      // wait_for_ext_suspend_completion(), but we can't call that while holding
2858      // the Threads_lock. The above tests are sufficient for our purposes
2859      // provided the walkability of the stack is stable - which it isn't
2860      // 100% but close enough for most practical purposes.
2861      throw_illegal_thread_state = true;
2862    } else {
2863      // Count all java activation, i.e., number of vframes
2864      for(vframeStream vfst(thr); !vfst.at_end(); vfst.next()) {
2865        // Native frames are not counted
2866        if (!vfst.method()->is_native()) count++;
2867       }
2868    }
2869  }
2870
2871  if (throw_illegal_thread_state) {
2872    THROW_MSG_0(vmSymbols::java_lang_IllegalThreadStateException(),
2873                "this thread is not suspended");
2874  }
2875  return count;
2876JVM_END
2877
2878// Consider: A better way to implement JVM_Interrupt() is to acquire
2879// Threads_lock to resolve the jthread into a Thread pointer, fetch
2880// Thread->platformevent, Thread->native_thr, Thread->parker, etc.,
2881// drop Threads_lock, and the perform the unpark() and thr_kill() operations
2882// outside the critical section.  Threads_lock is hot so we want to minimize
2883// the hold-time.  A cleaner interface would be to decompose interrupt into
2884// two steps.  The 1st phase, performed under Threads_lock, would return
2885// a closure that'd be invoked after Threads_lock was dropped.
2886// This tactic is safe as PlatformEvent and Parkers are type-stable (TSM) and
2887// admit spurious wakeups.
2888
2889JVM_ENTRY(void, JVM_Interrupt(JNIEnv* env, jobject jthread))
2890  JVMWrapper("JVM_Interrupt");
2891
2892  // Ensure that the C++ Thread and OSThread structures aren't freed before we operate
2893  oop java_thread = JNIHandles::resolve_non_null(jthread);
2894  MutexLockerEx ml(thread->threadObj() == java_thread ? NULL : Threads_lock);
2895  // We need to re-resolve the java_thread, since a GC might have happened during the
2896  // acquire of the lock
2897  JavaThread* thr = java_lang_Thread::thread(JNIHandles::resolve_non_null(jthread));
2898  if (thr != NULL) {
2899    Thread::interrupt(thr);
2900  }
2901JVM_END
2902
2903
2904JVM_QUICK_ENTRY(jboolean, JVM_IsInterrupted(JNIEnv* env, jobject jthread, jboolean clear_interrupted))
2905  JVMWrapper("JVM_IsInterrupted");
2906
2907  // Ensure that the C++ Thread and OSThread structures aren't freed before we operate
2908  oop java_thread = JNIHandles::resolve_non_null(jthread);
2909  MutexLockerEx ml(thread->threadObj() == java_thread ? NULL : Threads_lock);
2910  // We need to re-resolve the java_thread, since a GC might have happened during the
2911  // acquire of the lock
2912  JavaThread* thr = java_lang_Thread::thread(JNIHandles::resolve_non_null(jthread));
2913  if (thr == NULL) {
2914    return JNI_FALSE;
2915  } else {
2916    return (jboolean) Thread::is_interrupted(thr, clear_interrupted != 0);
2917  }
2918JVM_END
2919
2920
2921// Return true iff the current thread has locked the object passed in
2922
2923JVM_ENTRY(jboolean, JVM_HoldsLock(JNIEnv* env, jclass threadClass, jobject obj))
2924  JVMWrapper("JVM_HoldsLock");
2925  assert(THREAD->is_Java_thread(), "sanity check");
2926  if (obj == NULL) {
2927    THROW_(vmSymbols::java_lang_NullPointerException(), JNI_FALSE);
2928  }
2929  Handle h_obj(THREAD, JNIHandles::resolve(obj));
2930  return ObjectSynchronizer::current_thread_holds_lock((JavaThread*)THREAD, h_obj);
2931JVM_END
2932
2933
2934JVM_ENTRY(void, JVM_DumpAllStacks(JNIEnv* env, jclass))
2935  JVMWrapper("JVM_DumpAllStacks");
2936  VM_PrintThreads op;
2937  VMThread::execute(&op);
2938  if (JvmtiExport::should_post_data_dump()) {
2939    JvmtiExport::post_data_dump();
2940  }
2941JVM_END
2942
2943
2944// java.lang.SecurityManager ///////////////////////////////////////////////////////////////////////
2945
2946static bool is_trusted_frame(JavaThread* jthread, vframeStream* vfst) {
2947  assert(jthread->is_Java_thread(), "must be a Java thread");
2948  if (jthread->privileged_stack_top() == NULL) return false;
2949  if (jthread->privileged_stack_top()->frame_id() == vfst->frame_id()) {
2950    oop loader = jthread->privileged_stack_top()->class_loader();
2951    if (loader == NULL) return true;
2952    bool trusted = java_lang_ClassLoader::is_trusted_loader(loader);
2953    if (trusted) return true;
2954  }
2955  return false;
2956}
2957
2958JVM_ENTRY(jclass, JVM_CurrentLoadedClass(JNIEnv *env))
2959  JVMWrapper("JVM_CurrentLoadedClass");
2960  ResourceMark rm(THREAD);
2961
2962  for (vframeStream vfst(thread); !vfst.at_end(); vfst.next()) {
2963    // if a method in a class in a trusted loader is in a doPrivileged, return NULL
2964    bool trusted = is_trusted_frame(thread, &vfst);
2965    if (trusted) return NULL;
2966
2967    methodOop m = vfst.method();
2968    if (!m->is_native()) {
2969      klassOop holder = m->method_holder();
2970      oop      loader = instanceKlass::cast(holder)->class_loader();
2971      if (loader != NULL && !java_lang_ClassLoader::is_trusted_loader(loader)) {
2972        return (jclass) JNIHandles::make_local(env, Klass::cast(holder)->java_mirror());
2973      }
2974    }
2975  }
2976  return NULL;
2977JVM_END
2978
2979
2980JVM_ENTRY(jobject, JVM_CurrentClassLoader(JNIEnv *env))
2981  JVMWrapper("JVM_CurrentClassLoader");
2982  ResourceMark rm(THREAD);
2983
2984  for (vframeStream vfst(thread); !vfst.at_end(); vfst.next()) {
2985
2986    // if a method in a class in a trusted loader is in a doPrivileged, return NULL
2987    bool trusted = is_trusted_frame(thread, &vfst);
2988    if (trusted) return NULL;
2989
2990    methodOop m = vfst.method();
2991    if (!m->is_native()) {
2992      klassOop holder = m->method_holder();
2993      assert(holder->is_klass(), "just checking");
2994      oop loader = instanceKlass::cast(holder)->class_loader();
2995      if (loader != NULL && !java_lang_ClassLoader::is_trusted_loader(loader)) {
2996        return JNIHandles::make_local(env, loader);
2997      }
2998    }
2999  }
3000  return NULL;
3001JVM_END
3002
3003
3004// Utility object for collecting method holders walking down the stack
3005class KlassLink: public ResourceObj {
3006 public:
3007  KlassHandle klass;
3008  KlassLink*  next;
3009
3010  KlassLink(KlassHandle k) { klass = k; next = NULL; }
3011};
3012
3013
3014JVM_ENTRY(jobjectArray, JVM_GetClassContext(JNIEnv *env))
3015  JVMWrapper("JVM_GetClassContext");
3016  ResourceMark rm(THREAD);
3017  JvmtiVMObjectAllocEventCollector oam;
3018  // Collect linked list of (handles to) method holders
3019  KlassLink* first = NULL;
3020  KlassLink* last  = NULL;
3021  int depth = 0;
3022
3023  for(vframeStream vfst(thread); !vfst.at_end(); vfst.security_get_caller_frame(1)) {
3024    // Native frames are not returned
3025    if (!vfst.method()->is_native()) {
3026      klassOop holder = vfst.method()->method_holder();
3027      assert(holder->is_klass(), "just checking");
3028      depth++;
3029      KlassLink* l = new KlassLink(KlassHandle(thread, holder));
3030      if (first == NULL) {
3031        first = last = l;
3032      } else {
3033        last->next = l;
3034        last = l;
3035      }
3036    }
3037  }
3038
3039  // Create result array of type [Ljava/lang/Class;
3040  objArrayOop result = oopFactory::new_objArray(SystemDictionary::Class_klass(), depth, CHECK_NULL);
3041  // Fill in mirrors corresponding to method holders
3042  int index = 0;
3043  while (first != NULL) {
3044    result->obj_at_put(index++, Klass::cast(first->klass())->java_mirror());
3045    first = first->next;
3046  }
3047  assert(index == depth, "just checking");
3048
3049  return (jobjectArray) JNIHandles::make_local(env, result);
3050JVM_END
3051
3052
3053JVM_ENTRY(jint, JVM_ClassDepth(JNIEnv *env, jstring name))
3054  JVMWrapper("JVM_ClassDepth");
3055  ResourceMark rm(THREAD);
3056  Handle h_name (THREAD, JNIHandles::resolve_non_null(name));
3057  Handle class_name_str = java_lang_String::internalize_classname(h_name, CHECK_0);
3058
3059  const char* str = java_lang_String::as_utf8_string(class_name_str());
3060  symbolHandle class_name_sym =
3061                symbolHandle(THREAD, SymbolTable::probe(str, (int)strlen(str)));
3062  if (class_name_sym.is_null()) {
3063    return -1;
3064  }
3065
3066  int depth = 0;
3067
3068  for(vframeStream vfst(thread); !vfst.at_end(); vfst.next()) {
3069    if (!vfst.method()->is_native()) {
3070      klassOop holder = vfst.method()->method_holder();
3071      assert(holder->is_klass(), "just checking");
3072      if (instanceKlass::cast(holder)->name() == class_name_sym()) {
3073        return depth;
3074      }
3075      depth++;
3076    }
3077  }
3078  return -1;
3079JVM_END
3080
3081
3082JVM_ENTRY(jint, JVM_ClassLoaderDepth(JNIEnv *env))
3083  JVMWrapper("JVM_ClassLoaderDepth");
3084  ResourceMark rm(THREAD);
3085  int depth = 0;
3086  for (vframeStream vfst(thread); !vfst.at_end(); vfst.next()) {
3087    // if a method in a class in a trusted loader is in a doPrivileged, return -1
3088    bool trusted = is_trusted_frame(thread, &vfst);
3089    if (trusted) return -1;
3090
3091    methodOop m = vfst.method();
3092    if (!m->is_native()) {
3093      klassOop holder = m->method_holder();
3094      assert(holder->is_klass(), "just checking");
3095      oop loader = instanceKlass::cast(holder)->class_loader();
3096      if (loader != NULL && !java_lang_ClassLoader::is_trusted_loader(loader)) {
3097        return depth;
3098      }
3099      depth++;
3100    }
3101  }
3102  return -1;
3103JVM_END
3104
3105
3106// java.lang.Package ////////////////////////////////////////////////////////////////
3107
3108
3109JVM_ENTRY(jstring, JVM_GetSystemPackage(JNIEnv *env, jstring name))
3110  JVMWrapper("JVM_GetSystemPackage");
3111  ResourceMark rm(THREAD);
3112  JvmtiVMObjectAllocEventCollector oam;
3113  char* str = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(name));
3114  oop result = ClassLoader::get_system_package(str, CHECK_NULL);
3115  return (jstring) JNIHandles::make_local(result);
3116JVM_END
3117
3118
3119JVM_ENTRY(jobjectArray, JVM_GetSystemPackages(JNIEnv *env))
3120  JVMWrapper("JVM_GetSystemPackages");
3121  JvmtiVMObjectAllocEventCollector oam;
3122  objArrayOop result = ClassLoader::get_system_packages(CHECK_NULL);
3123  return (jobjectArray) JNIHandles::make_local(result);
3124JVM_END
3125
3126
3127// ObjectInputStream ///////////////////////////////////////////////////////////////
3128
3129bool force_verify_field_access(klassOop current_class, klassOop field_class, AccessFlags access, bool classloader_only) {
3130  if (current_class == NULL) {
3131    return true;
3132  }
3133  if ((current_class == field_class) || access.is_public()) {
3134    return true;
3135  }
3136
3137  if (access.is_protected()) {
3138    // See if current_class is a subclass of field_class
3139    if (Klass::cast(current_class)->is_subclass_of(field_class)) {
3140      return true;
3141    }
3142  }
3143
3144  return (!access.is_private() && instanceKlass::cast(current_class)->is_same_class_package(field_class));
3145}
3146
3147
3148// JVM_AllocateNewObject and JVM_AllocateNewArray are unused as of 1.4
3149JVM_ENTRY(jobject, JVM_AllocateNewObject(JNIEnv *env, jobject receiver, jclass currClass, jclass initClass))
3150  JVMWrapper("JVM_AllocateNewObject");
3151  JvmtiVMObjectAllocEventCollector oam;
3152  // Receiver is not used
3153  oop curr_mirror = JNIHandles::resolve_non_null(currClass);
3154  oop init_mirror = JNIHandles::resolve_non_null(initClass);
3155
3156  // Cannot instantiate primitive types
3157  if (java_lang_Class::is_primitive(curr_mirror) || java_lang_Class::is_primitive(init_mirror)) {
3158    ResourceMark rm(THREAD);
3159    THROW_0(vmSymbols::java_lang_InvalidClassException());
3160  }
3161
3162  // Arrays not allowed here, must use JVM_AllocateNewArray
3163  if (Klass::cast(java_lang_Class::as_klassOop(curr_mirror))->oop_is_javaArray() ||
3164      Klass::cast(java_lang_Class::as_klassOop(init_mirror))->oop_is_javaArray()) {
3165    ResourceMark rm(THREAD);
3166    THROW_0(vmSymbols::java_lang_InvalidClassException());
3167  }
3168
3169  instanceKlassHandle curr_klass (THREAD, java_lang_Class::as_klassOop(curr_mirror));
3170  instanceKlassHandle init_klass (THREAD, java_lang_Class::as_klassOop(init_mirror));
3171
3172  assert(curr_klass->is_subclass_of(init_klass()), "just checking");
3173
3174  // Interfaces, abstract classes, and java.lang.Class classes cannot be instantiated directly.
3175  curr_klass->check_valid_for_instantiation(false, CHECK_NULL);
3176
3177  // Make sure klass is initialized, since we are about to instantiate one of them.
3178  curr_klass->initialize(CHECK_NULL);
3179
3180 methodHandle m (THREAD,
3181                 init_klass->find_method(vmSymbols::object_initializer_name(),
3182                                         vmSymbols::void_method_signature()));
3183  if (m.is_null()) {
3184    ResourceMark rm(THREAD);
3185    THROW_MSG_0(vmSymbols::java_lang_NoSuchMethodError(),
3186                methodOopDesc::name_and_sig_as_C_string(Klass::cast(init_klass()),
3187                                          vmSymbols::object_initializer_name(),
3188                                          vmSymbols::void_method_signature()));
3189  }
3190
3191  if (curr_klass ==  init_klass && !m->is_public()) {
3192    // Calling the constructor for class 'curr_klass'.
3193    // Only allow calls to a public no-arg constructor.
3194    // This path corresponds to creating an Externalizable object.
3195    THROW_0(vmSymbols::java_lang_IllegalAccessException());
3196  }
3197
3198  if (!force_verify_field_access(curr_klass(), init_klass(), m->access_flags(), false)) {
3199    // subclass 'curr_klass' does not have access to no-arg constructor of 'initcb'
3200    THROW_0(vmSymbols::java_lang_IllegalAccessException());
3201  }
3202
3203  Handle obj = curr_klass->allocate_instance_handle(CHECK_NULL);
3204  // Call constructor m. This might call a constructor higher up in the hierachy
3205  JavaCalls::call_default_constructor(thread, m, obj, CHECK_NULL);
3206
3207  return JNIHandles::make_local(obj());
3208JVM_END
3209
3210
3211JVM_ENTRY(jobject, JVM_AllocateNewArray(JNIEnv *env, jobject obj, jclass currClass, jint length))
3212  JVMWrapper("JVM_AllocateNewArray");
3213  JvmtiVMObjectAllocEventCollector oam;
3214  oop mirror = JNIHandles::resolve_non_null(currClass);
3215
3216  if (java_lang_Class::is_primitive(mirror)) {
3217    THROW_0(vmSymbols::java_lang_InvalidClassException());
3218  }
3219  klassOop k = java_lang_Class::as_klassOop(mirror);
3220  oop result;
3221
3222  if (k->klass_part()->oop_is_typeArray()) {
3223    // typeArray
3224    result = typeArrayKlass::cast(k)->allocate(length, CHECK_NULL);
3225  } else if (k->klass_part()->oop_is_objArray()) {
3226    // objArray
3227    objArrayKlassHandle oak(THREAD, k);
3228    oak->initialize(CHECK_NULL); // make sure class is initialized (matches Classic VM behavior)
3229    result = oak->allocate(length, CHECK_NULL);
3230  } else {
3231    THROW_0(vmSymbols::java_lang_InvalidClassException());
3232  }
3233  return JNIHandles::make_local(env, result);
3234JVM_END
3235
3236
3237// Return the first non-null class loader up the execution stack, or null
3238// if only code from the null class loader is on the stack.
3239
3240JVM_ENTRY(jobject, JVM_LatestUserDefinedLoader(JNIEnv *env))
3241  for (vframeStream vfst(thread); !vfst.at_end(); vfst.next()) {
3242    // UseNewReflection
3243    vfst.skip_reflection_related_frames(); // Only needed for 1.4 reflection
3244    klassOop holder = vfst.method()->method_holder();
3245    oop loader = instanceKlass::cast(holder)->class_loader();
3246    if (loader != NULL) {
3247      return JNIHandles::make_local(env, loader);
3248    }
3249  }
3250  return NULL;
3251JVM_END
3252
3253
3254// Load a class relative to the most recent class on the stack  with a non-null
3255// classloader.
3256// This function has been deprecated and should not be considered part of the
3257// specified JVM interface.
3258
3259JVM_ENTRY(jclass, JVM_LoadClass0(JNIEnv *env, jobject receiver,
3260                                 jclass currClass, jstring currClassName))
3261  JVMWrapper("JVM_LoadClass0");
3262  // Receiver is not used
3263  ResourceMark rm(THREAD);
3264
3265  // Class name argument is not guaranteed to be in internal format
3266  Handle classname (THREAD, JNIHandles::resolve_non_null(currClassName));
3267  Handle string = java_lang_String::internalize_classname(classname, CHECK_NULL);
3268
3269  const char* str = java_lang_String::as_utf8_string(string());
3270
3271  if (str == NULL || (int)strlen(str) > symbolOopDesc::max_length()) {
3272    // It's impossible to create this class;  the name cannot fit
3273    // into the constant pool.
3274    THROW_MSG_0(vmSymbols::java_lang_NoClassDefFoundError(), str);
3275  }
3276
3277  symbolHandle name = oopFactory::new_symbol_handle(str, CHECK_NULL);
3278  Handle curr_klass (THREAD, JNIHandles::resolve(currClass));
3279  // Find the most recent class on the stack with a non-null classloader
3280  oop loader = NULL;
3281  oop protection_domain = NULL;
3282  if (curr_klass.is_null()) {
3283    for (vframeStream vfst(thread);
3284         !vfst.at_end() && loader == NULL;
3285         vfst.next()) {
3286      if (!vfst.method()->is_native()) {
3287        klassOop holder = vfst.method()->method_holder();
3288        loader             = instanceKlass::cast(holder)->class_loader();
3289        protection_domain  = instanceKlass::cast(holder)->protection_domain();
3290      }
3291    }
3292  } else {
3293    klassOop curr_klass_oop = java_lang_Class::as_klassOop(curr_klass());
3294    loader            = instanceKlass::cast(curr_klass_oop)->class_loader();
3295    protection_domain = instanceKlass::cast(curr_klass_oop)->protection_domain();
3296  }
3297  Handle h_loader(THREAD, loader);
3298  Handle h_prot  (THREAD, protection_domain);
3299  jclass result =  find_class_from_class_loader(env, name, true, h_loader, h_prot,
3300                                                false, thread);
3301  if (TraceClassResolution && result != NULL) {
3302    trace_class_resolution(java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(result)));
3303  }
3304  return result;
3305JVM_END
3306
3307
3308// Array ///////////////////////////////////////////////////////////////////////////////////////////
3309
3310
3311// resolve array handle and check arguments
3312static inline arrayOop check_array(JNIEnv *env, jobject arr, bool type_array_only, TRAPS) {
3313  if (arr == NULL) {
3314    THROW_0(vmSymbols::java_lang_NullPointerException());
3315  }
3316  oop a = JNIHandles::resolve_non_null(arr);
3317  if (!a->is_javaArray() || (type_array_only && !a->is_typeArray())) {
3318    THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Argument is not an array");
3319  }
3320  return arrayOop(a);
3321}
3322
3323
3324JVM_ENTRY(jint, JVM_GetArrayLength(JNIEnv *env, jobject arr))
3325  JVMWrapper("JVM_GetArrayLength");
3326  arrayOop a = check_array(env, arr, false, CHECK_0);
3327  return a->length();
3328JVM_END
3329
3330
3331JVM_ENTRY(jobject, JVM_GetArrayElement(JNIEnv *env, jobject arr, jint index))
3332  JVMWrapper("JVM_Array_Get");
3333  JvmtiVMObjectAllocEventCollector oam;
3334  arrayOop a = check_array(env, arr, false, CHECK_NULL);
3335  jvalue value;
3336  BasicType type = Reflection::array_get(&value, a, index, CHECK_NULL);
3337  oop box = Reflection::box(&value, type, CHECK_NULL);
3338  return JNIHandles::make_local(env, box);
3339JVM_END
3340
3341
3342JVM_ENTRY(jvalue, JVM_GetPrimitiveArrayElement(JNIEnv *env, jobject arr, jint index, jint wCode))
3343  JVMWrapper("JVM_GetPrimitiveArrayElement");
3344  jvalue value;
3345  value.i = 0; // to initialize value before getting used in CHECK
3346  arrayOop a = check_array(env, arr, true, CHECK_(value));
3347  assert(a->is_typeArray(), "just checking");
3348  BasicType type = Reflection::array_get(&value, a, index, CHECK_(value));
3349  BasicType wide_type = (BasicType) wCode;
3350  if (type != wide_type) {
3351    Reflection::widen(&value, type, wide_type, CHECK_(value));
3352  }
3353  return value;
3354JVM_END
3355
3356
3357JVM_ENTRY(void, JVM_SetArrayElement(JNIEnv *env, jobject arr, jint index, jobject val))
3358  JVMWrapper("JVM_SetArrayElement");
3359  arrayOop a = check_array(env, arr, false, CHECK);
3360  oop box = JNIHandles::resolve(val);
3361  jvalue value;
3362  value.i = 0; // to initialize value before getting used in CHECK
3363  BasicType value_type;
3364  if (a->is_objArray()) {
3365    // Make sure we do no unbox e.g. java/lang/Integer instances when storing into an object array
3366    value_type = Reflection::unbox_for_regular_object(box, &value);
3367  } else {
3368    value_type = Reflection::unbox_for_primitive(box, &value, CHECK);
3369  }
3370  Reflection::array_set(&value, a, index, value_type, CHECK);
3371JVM_END
3372
3373
3374JVM_ENTRY(void, JVM_SetPrimitiveArrayElement(JNIEnv *env, jobject arr, jint index, jvalue v, unsigned char vCode))
3375  JVMWrapper("JVM_SetPrimitiveArrayElement");
3376  arrayOop a = check_array(env, arr, true, CHECK);
3377  assert(a->is_typeArray(), "just checking");
3378  BasicType value_type = (BasicType) vCode;
3379  Reflection::array_set(&v, a, index, value_type, CHECK);
3380JVM_END
3381
3382
3383JVM_ENTRY(jobject, JVM_NewArray(JNIEnv *env, jclass eltClass, jint length))
3384  JVMWrapper("JVM_NewArray");
3385  JvmtiVMObjectAllocEventCollector oam;
3386  oop element_mirror = JNIHandles::resolve(eltClass);
3387  oop result = Reflection::reflect_new_array(element_mirror, length, CHECK_NULL);
3388  return JNIHandles::make_local(env, result);
3389JVM_END
3390
3391
3392JVM_ENTRY(jobject, JVM_NewMultiArray(JNIEnv *env, jclass eltClass, jintArray dim))
3393  JVMWrapper("JVM_NewMultiArray");
3394  JvmtiVMObjectAllocEventCollector oam;
3395  arrayOop dim_array = check_array(env, dim, true, CHECK_NULL);
3396  oop element_mirror = JNIHandles::resolve(eltClass);
3397  assert(dim_array->is_typeArray(), "just checking");
3398  oop result = Reflection::reflect_new_multi_array(element_mirror, typeArrayOop(dim_array), CHECK_NULL);
3399  return JNIHandles::make_local(env, result);
3400JVM_END
3401
3402
3403// Networking library support ////////////////////////////////////////////////////////////////////
3404
3405JVM_LEAF(jint, JVM_InitializeSocketLibrary())
3406  JVMWrapper("JVM_InitializeSocketLibrary");
3407  return hpi::initialize_socket_library();
3408JVM_END
3409
3410
3411JVM_LEAF(jint, JVM_Socket(jint domain, jint type, jint protocol))
3412  JVMWrapper("JVM_Socket");
3413  return hpi::socket(domain, type, protocol);
3414JVM_END
3415
3416
3417JVM_LEAF(jint, JVM_SocketClose(jint fd))
3418  JVMWrapper2("JVM_SocketClose (0x%x)", fd);
3419  //%note jvm_r6
3420  return hpi::socket_close(fd);
3421JVM_END
3422
3423
3424JVM_LEAF(jint, JVM_SocketShutdown(jint fd, jint howto))
3425  JVMWrapper2("JVM_SocketShutdown (0x%x)", fd);
3426  //%note jvm_r6
3427  return hpi::socket_shutdown(fd, howto);
3428JVM_END
3429
3430
3431JVM_LEAF(jint, JVM_Recv(jint fd, char *buf, jint nBytes, jint flags))
3432  JVMWrapper2("JVM_Recv (0x%x)", fd);
3433  //%note jvm_r6
3434  return hpi::recv(fd, buf, nBytes, flags);
3435JVM_END
3436
3437
3438JVM_LEAF(jint, JVM_Send(jint fd, char *buf, jint nBytes, jint flags))
3439  JVMWrapper2("JVM_Send (0x%x)", fd);
3440  //%note jvm_r6
3441  return hpi::send(fd, buf, nBytes, flags);
3442JVM_END
3443
3444
3445JVM_LEAF(jint, JVM_Timeout(int fd, long timeout))
3446  JVMWrapper2("JVM_Timeout (0x%x)", fd);
3447  //%note jvm_r6
3448  return hpi::timeout(fd, timeout);
3449JVM_END
3450
3451
3452JVM_LEAF(jint, JVM_Listen(jint fd, jint count))
3453  JVMWrapper2("JVM_Listen (0x%x)", fd);
3454  //%note jvm_r6
3455  return hpi::listen(fd, count);
3456JVM_END
3457
3458
3459JVM_LEAF(jint, JVM_Connect(jint fd, struct sockaddr *him, jint len))
3460  JVMWrapper2("JVM_Connect (0x%x)", fd);
3461  //%note jvm_r6
3462  return hpi::connect(fd, him, len);
3463JVM_END
3464
3465
3466JVM_LEAF(jint, JVM_Bind(jint fd, struct sockaddr *him, jint len))
3467  JVMWrapper2("JVM_Bind (0x%x)", fd);
3468  //%note jvm_r6
3469  return hpi::bind(fd, him, len);
3470JVM_END
3471
3472
3473JVM_LEAF(jint, JVM_Accept(jint fd, struct sockaddr *him, jint *len))
3474  JVMWrapper2("JVM_Accept (0x%x)", fd);
3475  //%note jvm_r6
3476  return hpi::accept(fd, him, (int *)len);
3477JVM_END
3478
3479
3480JVM_LEAF(jint, JVM_RecvFrom(jint fd, char *buf, int nBytes, int flags, struct sockaddr *from, int *fromlen))
3481  JVMWrapper2("JVM_RecvFrom (0x%x)", fd);
3482  //%note jvm_r6
3483  return hpi::recvfrom(fd, buf, nBytes, flags, from, fromlen);
3484JVM_END
3485
3486
3487JVM_LEAF(jint, JVM_GetSockName(jint fd, struct sockaddr *him, int *len))
3488  JVMWrapper2("JVM_GetSockName (0x%x)", fd);
3489  //%note jvm_r6
3490  return hpi::get_sock_name(fd, him, len);
3491JVM_END
3492
3493
3494JVM_LEAF(jint, JVM_SendTo(jint fd, char *buf, int len, int flags, struct sockaddr *to, int tolen))
3495  JVMWrapper2("JVM_SendTo (0x%x)", fd);
3496  //%note jvm_r6
3497  return hpi::sendto(fd, buf, len, flags, to, tolen);
3498JVM_END
3499
3500
3501JVM_LEAF(jint, JVM_SocketAvailable(jint fd, jint *pbytes))
3502  JVMWrapper2("JVM_SocketAvailable (0x%x)", fd);
3503  //%note jvm_r6
3504  return hpi::socket_available(fd, pbytes);
3505JVM_END
3506
3507
3508JVM_LEAF(jint, JVM_GetSockOpt(jint fd, int level, int optname, char *optval, int *optlen))
3509  JVMWrapper2("JVM_GetSockOpt (0x%x)", fd);
3510  //%note jvm_r6
3511  return hpi::get_sock_opt(fd, level, optname, optval, optlen);
3512JVM_END
3513
3514
3515JVM_LEAF(jint, JVM_SetSockOpt(jint fd, int level, int optname, const char *optval, int optlen))
3516  JVMWrapper2("JVM_GetSockOpt (0x%x)", fd);
3517  //%note jvm_r6
3518  return hpi::set_sock_opt(fd, level, optname, optval, optlen);
3519JVM_END
3520
3521JVM_LEAF(int, JVM_GetHostName(char* name, int namelen))
3522  JVMWrapper("JVM_GetHostName");
3523  return hpi::get_host_name(name, namelen);
3524JVM_END
3525
3526#ifdef _WINDOWS
3527
3528JVM_LEAF(struct hostent*, JVM_GetHostByAddr(const char* name, int len, int type))
3529  JVMWrapper("JVM_GetHostByAddr");
3530  return hpi::get_host_by_addr(name, len, type);
3531JVM_END
3532
3533
3534JVM_LEAF(struct hostent*, JVM_GetHostByName(char* name))
3535  JVMWrapper("JVM_GetHostByName");
3536  return hpi::get_host_by_name(name);
3537JVM_END
3538
3539
3540JVM_LEAF(struct protoent*, JVM_GetProtoByName(char* name))
3541  JVMWrapper("JVM_GetProtoByName");
3542  return hpi::get_proto_by_name(name);
3543JVM_END
3544
3545#endif
3546
3547// Library support ///////////////////////////////////////////////////////////////////////////
3548
3549JVM_ENTRY_NO_ENV(void*, JVM_LoadLibrary(const char* name))
3550  //%note jvm_ct
3551  JVMWrapper2("JVM_LoadLibrary (%s)", name);
3552  char ebuf[1024];
3553  void *load_result;
3554  {
3555    ThreadToNativeFromVM ttnfvm(thread);
3556    load_result = hpi::dll_load(name, ebuf, sizeof ebuf);
3557  }
3558  if (load_result == NULL) {
3559    char msg[1024];
3560    jio_snprintf(msg, sizeof msg, "%s: %s", name, ebuf);
3561    // Since 'ebuf' may contain a string encoded using
3562    // platform encoding scheme, we need to pass
3563    // Exceptions::unsafe_to_utf8 to the new_exception method
3564    // as the last argument. See bug 6367357.
3565    Handle h_exception =
3566      Exceptions::new_exception(thread,
3567                                vmSymbols::java_lang_UnsatisfiedLinkError(),
3568                                msg, Exceptions::unsafe_to_utf8);
3569
3570    THROW_HANDLE_0(h_exception);
3571  }
3572  return load_result;
3573JVM_END
3574
3575
3576JVM_LEAF(void, JVM_UnloadLibrary(void* handle))
3577  JVMWrapper("JVM_UnloadLibrary");
3578  hpi::dll_unload(handle);
3579JVM_END
3580
3581
3582JVM_LEAF(void*, JVM_FindLibraryEntry(void* handle, const char* name))
3583  JVMWrapper2("JVM_FindLibraryEntry (%s)", name);
3584  return hpi::dll_lookup(handle, name);
3585JVM_END
3586
3587// Floating point support ////////////////////////////////////////////////////////////////////
3588
3589JVM_LEAF(jboolean, JVM_IsNaN(jdouble a))
3590  JVMWrapper("JVM_IsNaN");
3591  return g_isnan(a);
3592JVM_END
3593
3594
3595
3596// JNI version ///////////////////////////////////////////////////////////////////////////////
3597
3598JVM_LEAF(jboolean, JVM_IsSupportedJNIVersion(jint version))
3599  JVMWrapper2("JVM_IsSupportedJNIVersion (%d)", version);
3600  return Threads::is_supported_jni_version_including_1_1(version);
3601JVM_END
3602
3603
3604// String support ///////////////////////////////////////////////////////////////////////////
3605
3606JVM_ENTRY(jstring, JVM_InternString(JNIEnv *env, jstring str))
3607  JVMWrapper("JVM_InternString");
3608  JvmtiVMObjectAllocEventCollector oam;
3609  if (str == NULL) return NULL;
3610  oop string = JNIHandles::resolve_non_null(str);
3611  oop result = StringTable::intern(string, CHECK_NULL);
3612  return (jstring) JNIHandles::make_local(env, result);
3613JVM_END
3614
3615
3616// Raw monitor support //////////////////////////////////////////////////////////////////////
3617
3618// The lock routine below calls lock_without_safepoint_check in order to get a raw lock
3619// without interfering with the safepoint mechanism. The routines are not JVM_LEAF because
3620// they might be called by non-java threads. The JVM_LEAF installs a NoHandleMark check
3621// that only works with java threads.
3622
3623
3624JNIEXPORT void* JNICALL JVM_RawMonitorCreate(void) {
3625  VM_Exit::block_if_vm_exited();
3626  JVMWrapper("JVM_RawMonitorCreate");
3627  return new Mutex(Mutex::native, "JVM_RawMonitorCreate");
3628}
3629
3630
3631JNIEXPORT void JNICALL  JVM_RawMonitorDestroy(void *mon) {
3632  VM_Exit::block_if_vm_exited();
3633  JVMWrapper("JVM_RawMonitorDestroy");
3634  delete ((Mutex*) mon);
3635}
3636
3637
3638JNIEXPORT jint JNICALL JVM_RawMonitorEnter(void *mon) {
3639  VM_Exit::block_if_vm_exited();
3640  JVMWrapper("JVM_RawMonitorEnter");
3641  ((Mutex*) mon)->jvm_raw_lock();
3642  return 0;
3643}
3644
3645
3646JNIEXPORT void JNICALL JVM_RawMonitorExit(void *mon) {
3647  VM_Exit::block_if_vm_exited();
3648  JVMWrapper("JVM_RawMonitorExit");
3649  ((Mutex*) mon)->jvm_raw_unlock();
3650}
3651
3652
3653// Support for Serialization
3654
3655typedef jfloat  (JNICALL *IntBitsToFloatFn  )(JNIEnv* env, jclass cb, jint    value);
3656typedef jdouble (JNICALL *LongBitsToDoubleFn)(JNIEnv* env, jclass cb, jlong   value);
3657typedef jint    (JNICALL *FloatToIntBitsFn  )(JNIEnv* env, jclass cb, jfloat  value);
3658typedef jlong   (JNICALL *DoubleToLongBitsFn)(JNIEnv* env, jclass cb, jdouble value);
3659
3660static IntBitsToFloatFn   int_bits_to_float_fn   = NULL;
3661static LongBitsToDoubleFn long_bits_to_double_fn = NULL;
3662static FloatToIntBitsFn   float_to_int_bits_fn   = NULL;
3663static DoubleToLongBitsFn double_to_long_bits_fn = NULL;
3664
3665
3666void initialize_converter_functions() {
3667  if (JDK_Version::is_gte_jdk14x_version()) {
3668    // These functions only exist for compatibility with 1.3.1 and earlier
3669    return;
3670  }
3671
3672  // called from universe_post_init()
3673  assert(
3674    int_bits_to_float_fn   == NULL &&
3675    long_bits_to_double_fn == NULL &&
3676    float_to_int_bits_fn   == NULL &&
3677    double_to_long_bits_fn == NULL ,
3678    "initialization done twice"
3679  );
3680  // initialize
3681  int_bits_to_float_fn   = CAST_TO_FN_PTR(IntBitsToFloatFn  , NativeLookup::base_library_lookup("java/lang/Float" , "intBitsToFloat"  , "(I)F"));
3682  long_bits_to_double_fn = CAST_TO_FN_PTR(LongBitsToDoubleFn, NativeLookup::base_library_lookup("java/lang/Double", "longBitsToDouble", "(J)D"));
3683  float_to_int_bits_fn   = CAST_TO_FN_PTR(FloatToIntBitsFn  , NativeLookup::base_library_lookup("java/lang/Float" , "floatToIntBits"  , "(F)I"));
3684  double_to_long_bits_fn = CAST_TO_FN_PTR(DoubleToLongBitsFn, NativeLookup::base_library_lookup("java/lang/Double", "doubleToLongBits", "(D)J"));
3685  // verify
3686  assert(
3687    int_bits_to_float_fn   != NULL &&
3688    long_bits_to_double_fn != NULL &&
3689    float_to_int_bits_fn   != NULL &&
3690    double_to_long_bits_fn != NULL ,
3691    "initialization failed"
3692  );
3693}
3694
3695
3696// Serialization
3697JVM_ENTRY(void, JVM_SetPrimitiveFieldValues(JNIEnv *env, jclass cb, jobject obj,
3698                                            jlongArray fieldIDs, jcharArray typecodes, jbyteArray data))
3699  assert(!JDK_Version::is_gte_jdk14x_version(), "should only be used in 1.3.1 and earlier");
3700
3701  typeArrayOop tcodes = typeArrayOop(JNIHandles::resolve(typecodes));
3702  typeArrayOop dbuf   = typeArrayOop(JNIHandles::resolve(data));
3703  typeArrayOop fids   = typeArrayOop(JNIHandles::resolve(fieldIDs));
3704  oop          o      = JNIHandles::resolve(obj);
3705
3706  if (o == NULL || fids == NULL  || dbuf == NULL  || tcodes == NULL) {
3707    THROW(vmSymbols::java_lang_NullPointerException());
3708  }
3709
3710  jsize nfids = fids->length();
3711  if (nfids == 0) return;
3712
3713  if (tcodes->length() < nfids) {
3714    THROW(vmSymbols::java_lang_ArrayIndexOutOfBoundsException());
3715  }
3716
3717  jsize off = 0;
3718  /* loop through fields, setting values */
3719  for (jsize i = 0; i < nfids; i++) {
3720    jfieldID fid = (jfieldID)(intptr_t) fids->long_at(i);
3721    int field_offset;
3722    if (fid != NULL) {
3723      // NULL is a legal value for fid, but retrieving the field offset
3724      // trigger assertion in that case
3725      field_offset = jfieldIDWorkaround::from_instance_jfieldID(o->klass(), fid);
3726    }
3727
3728    switch (tcodes->char_at(i)) {
3729      case 'Z':
3730        if (fid != NULL) {
3731          jboolean val = (dbuf->byte_at(off) != 0) ? JNI_TRUE : JNI_FALSE;
3732          o->bool_field_put(field_offset, val);
3733        }
3734        off++;
3735        break;
3736
3737      case 'B':
3738        if (fid != NULL) {
3739          o->byte_field_put(field_offset, dbuf->byte_at(off));
3740        }
3741        off++;
3742        break;
3743
3744      case 'C':
3745        if (fid != NULL) {
3746          jchar val = ((dbuf->byte_at(off + 0) & 0xFF) << 8)
3747                    + ((dbuf->byte_at(off + 1) & 0xFF) << 0);
3748          o->char_field_put(field_offset, val);
3749        }
3750        off += 2;
3751        break;
3752
3753      case 'S':
3754        if (fid != NULL) {
3755          jshort val = ((dbuf->byte_at(off + 0) & 0xFF) << 8)
3756                     + ((dbuf->byte_at(off + 1) & 0xFF) << 0);
3757          o->short_field_put(field_offset, val);
3758        }
3759        off += 2;
3760        break;
3761
3762      case 'I':
3763        if (fid != NULL) {
3764          jint ival = ((dbuf->byte_at(off + 0) & 0xFF) << 24)
3765                    + ((dbuf->byte_at(off + 1) & 0xFF) << 16)
3766                    + ((dbuf->byte_at(off + 2) & 0xFF) << 8)
3767                    + ((dbuf->byte_at(off + 3) & 0xFF) << 0);
3768          o->int_field_put(field_offset, ival);
3769        }
3770        off += 4;
3771        break;
3772
3773      case 'F':
3774        if (fid != NULL) {
3775          jint ival = ((dbuf->byte_at(off + 0) & 0xFF) << 24)
3776                    + ((dbuf->byte_at(off + 1) & 0xFF) << 16)
3777                    + ((dbuf->byte_at(off + 2) & 0xFF) << 8)
3778                    + ((dbuf->byte_at(off + 3) & 0xFF) << 0);
3779          jfloat fval = (*int_bits_to_float_fn)(env, NULL, ival);
3780          o->float_field_put(field_offset, fval);
3781        }
3782        off += 4;
3783        break;
3784
3785      case 'J':
3786        if (fid != NULL) {
3787          jlong lval = (((jlong) dbuf->byte_at(off + 0) & 0xFF) << 56)
3788                     + (((jlong) dbuf->byte_at(off + 1) & 0xFF) << 48)
3789                     + (((jlong) dbuf->byte_at(off + 2) & 0xFF) << 40)
3790                     + (((jlong) dbuf->byte_at(off + 3) & 0xFF) << 32)
3791                     + (((jlong) dbuf->byte_at(off + 4) & 0xFF) << 24)
3792                     + (((jlong) dbuf->byte_at(off + 5) & 0xFF) << 16)
3793                     + (((jlong) dbuf->byte_at(off + 6) & 0xFF) << 8)
3794                     + (((jlong) dbuf->byte_at(off + 7) & 0xFF) << 0);
3795          o->long_field_put(field_offset, lval);
3796        }
3797        off += 8;
3798        break;
3799
3800      case 'D':
3801        if (fid != NULL) {
3802          jlong lval = (((jlong) dbuf->byte_at(off + 0) & 0xFF) << 56)
3803                     + (((jlong) dbuf->byte_at(off + 1) & 0xFF) << 48)
3804                     + (((jlong) dbuf->byte_at(off + 2) & 0xFF) << 40)
3805                     + (((jlong) dbuf->byte_at(off + 3) & 0xFF) << 32)
3806                     + (((jlong) dbuf->byte_at(off + 4) & 0xFF) << 24)
3807                     + (((jlong) dbuf->byte_at(off + 5) & 0xFF) << 16)
3808                     + (((jlong) dbuf->byte_at(off + 6) & 0xFF) << 8)
3809                     + (((jlong) dbuf->byte_at(off + 7) & 0xFF) << 0);
3810          jdouble dval = (*long_bits_to_double_fn)(env, NULL, lval);
3811          o->double_field_put(field_offset, dval);
3812        }
3813        off += 8;
3814        break;
3815
3816      default:
3817        // Illegal typecode
3818        THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "illegal typecode");
3819    }
3820  }
3821JVM_END
3822
3823
3824JVM_ENTRY(void, JVM_GetPrimitiveFieldValues(JNIEnv *env, jclass cb, jobject obj,
3825                            jlongArray fieldIDs, jcharArray typecodes, jbyteArray data))
3826  assert(!JDK_Version::is_gte_jdk14x_version(), "should only be used in 1.3.1 and earlier");
3827
3828  typeArrayOop tcodes = typeArrayOop(JNIHandles::resolve(typecodes));
3829  typeArrayOop dbuf   = typeArrayOop(JNIHandles::resolve(data));
3830  typeArrayOop fids   = typeArrayOop(JNIHandles::resolve(fieldIDs));
3831  oop          o      = JNIHandles::resolve(obj);
3832
3833  if (o == NULL || fids == NULL  || dbuf == NULL  || tcodes == NULL) {
3834    THROW(vmSymbols::java_lang_NullPointerException());
3835  }
3836
3837  jsize nfids = fids->length();
3838  if (nfids == 0) return;
3839
3840  if (tcodes->length() < nfids) {
3841    THROW(vmSymbols::java_lang_ArrayIndexOutOfBoundsException());
3842  }
3843
3844  /* loop through fields, fetching values */
3845  jsize off = 0;
3846  for (jsize i = 0; i < nfids; i++) {
3847    jfieldID fid = (jfieldID)(intptr_t) fids->long_at(i);
3848    if (fid == NULL) {
3849      THROW(vmSymbols::java_lang_NullPointerException());
3850    }
3851    int field_offset = jfieldIDWorkaround::from_instance_jfieldID(o->klass(), fid);
3852
3853     switch (tcodes->char_at(i)) {
3854       case 'Z':
3855         {
3856           jboolean val = o->bool_field(field_offset);
3857           dbuf->byte_at_put(off++, (val != 0) ? 1 : 0);
3858         }
3859         break;
3860
3861       case 'B':
3862         dbuf->byte_at_put(off++, o->byte_field(field_offset));
3863         break;
3864
3865       case 'C':
3866         {
3867           jchar val = o->char_field(field_offset);
3868           dbuf->byte_at_put(off++, (val >> 8) & 0xFF);
3869           dbuf->byte_at_put(off++, (val >> 0) & 0xFF);
3870         }
3871         break;
3872
3873       case 'S':
3874         {
3875           jshort val = o->short_field(field_offset);
3876           dbuf->byte_at_put(off++, (val >> 8) & 0xFF);
3877           dbuf->byte_at_put(off++, (val >> 0) & 0xFF);
3878         }
3879         break;
3880
3881       case 'I':
3882         {
3883           jint val = o->int_field(field_offset);
3884           dbuf->byte_at_put(off++, (val >> 24) & 0xFF);
3885           dbuf->byte_at_put(off++, (val >> 16) & 0xFF);
3886           dbuf->byte_at_put(off++, (val >> 8)  & 0xFF);
3887           dbuf->byte_at_put(off++, (val >> 0)  & 0xFF);
3888         }
3889         break;
3890
3891       case 'F':
3892         {
3893           jfloat fval = o->float_field(field_offset);
3894           jint ival = (*float_to_int_bits_fn)(env, NULL, fval);
3895           dbuf->byte_at_put(off++, (ival >> 24) & 0xFF);
3896           dbuf->byte_at_put(off++, (ival >> 16) & 0xFF);
3897           dbuf->byte_at_put(off++, (ival >> 8)  & 0xFF);
3898           dbuf->byte_at_put(off++, (ival >> 0)  & 0xFF);
3899         }
3900         break;
3901
3902       case 'J':
3903         {
3904           jlong val = o->long_field(field_offset);
3905           dbuf->byte_at_put(off++, (val >> 56) & 0xFF);
3906           dbuf->byte_at_put(off++, (val >> 48) & 0xFF);
3907           dbuf->byte_at_put(off++, (val >> 40) & 0xFF);
3908           dbuf->byte_at_put(off++, (val >> 32) & 0xFF);
3909           dbuf->byte_at_put(off++, (val >> 24) & 0xFF);
3910           dbuf->byte_at_put(off++, (val >> 16) & 0xFF);
3911           dbuf->byte_at_put(off++, (val >> 8)  & 0xFF);
3912           dbuf->byte_at_put(off++, (val >> 0)  & 0xFF);
3913         }
3914         break;
3915
3916       case 'D':
3917         {
3918           jdouble dval = o->double_field(field_offset);
3919           jlong lval = (*double_to_long_bits_fn)(env, NULL, dval);
3920           dbuf->byte_at_put(off++, (lval >> 56) & 0xFF);
3921           dbuf->byte_at_put(off++, (lval >> 48) & 0xFF);
3922           dbuf->byte_at_put(off++, (lval >> 40) & 0xFF);
3923           dbuf->byte_at_put(off++, (lval >> 32) & 0xFF);
3924           dbuf->byte_at_put(off++, (lval >> 24) & 0xFF);
3925           dbuf->byte_at_put(off++, (lval >> 16) & 0xFF);
3926           dbuf->byte_at_put(off++, (lval >> 8)  & 0xFF);
3927           dbuf->byte_at_put(off++, (lval >> 0)  & 0xFF);
3928         }
3929         break;
3930
3931       default:
3932         // Illegal typecode
3933         THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "illegal typecode");
3934     }
3935  }
3936JVM_END
3937
3938
3939// Shared JNI/JVM entry points //////////////////////////////////////////////////////////////
3940
3941jclass find_class_from_class_loader(JNIEnv* env, symbolHandle name, jboolean init, Handle loader, Handle protection_domain, jboolean throwError, TRAPS) {
3942  // Security Note:
3943  //   The Java level wrapper will perform the necessary security check allowing
3944  //   us to pass the NULL as the initiating class loader.
3945  klassOop klass = SystemDictionary::resolve_or_fail(name, loader, protection_domain, throwError != 0, CHECK_NULL);
3946
3947  KlassHandle klass_handle(THREAD, klass);
3948  // Check if we should initialize the class
3949  if (init && klass_handle->oop_is_instance()) {
3950    klass_handle->initialize(CHECK_NULL);
3951  }
3952  return (jclass) JNIHandles::make_local(env, klass_handle->java_mirror());
3953}
3954
3955
3956// Internal SQE debugging support ///////////////////////////////////////////////////////////
3957
3958#ifndef PRODUCT
3959
3960extern "C" {
3961  JNIEXPORT jboolean JNICALL JVM_AccessVMBooleanFlag(const char* name, jboolean* value, jboolean is_get);
3962  JNIEXPORT jboolean JNICALL JVM_AccessVMIntFlag(const char* name, jint* value, jboolean is_get);
3963  JNIEXPORT void JNICALL JVM_VMBreakPoint(JNIEnv *env, jobject obj);
3964}
3965
3966JVM_LEAF(jboolean, JVM_AccessVMBooleanFlag(const char* name, jboolean* value, jboolean is_get))
3967  JVMWrapper("JVM_AccessBoolVMFlag");
3968  return is_get ? CommandLineFlags::boolAt((char*) name, (bool*) value) : CommandLineFlags::boolAtPut((char*) name, (bool*) value, INTERNAL);
3969JVM_END
3970
3971JVM_LEAF(jboolean, JVM_AccessVMIntFlag(const char* name, jint* value, jboolean is_get))
3972  JVMWrapper("JVM_AccessVMIntFlag");
3973  intx v;
3974  jboolean result = is_get ? CommandLineFlags::intxAt((char*) name, &v) : CommandLineFlags::intxAtPut((char*) name, &v, INTERNAL);
3975  *value = (jint)v;
3976  return result;
3977JVM_END
3978
3979
3980JVM_ENTRY(void, JVM_VMBreakPoint(JNIEnv *env, jobject obj))
3981  JVMWrapper("JVM_VMBreakPoint");
3982  oop the_obj = JNIHandles::resolve(obj);
3983  BREAKPOINT;
3984JVM_END
3985
3986
3987#endif
3988
3989
3990//---------------------------------------------------------------------------
3991//
3992// Support for old native code-based reflection (pre-JDK 1.4)
3993// Disabled by default in the product build.
3994//
3995// See reflection.hpp for information on SUPPORT_OLD_REFLECTION
3996//
3997//---------------------------------------------------------------------------
3998
3999#ifdef SUPPORT_OLD_REFLECTION
4000
4001JVM_ENTRY(jobjectArray, JVM_GetClassFields(JNIEnv *env, jclass cls, jint which))
4002  JVMWrapper("JVM_GetClassFields");
4003  JvmtiVMObjectAllocEventCollector oam;
4004  oop mirror = JNIHandles::resolve_non_null(cls);
4005  objArrayOop result = Reflection::reflect_fields(mirror, which, CHECK_NULL);
4006  return (jobjectArray) JNIHandles::make_local(env, result);
4007JVM_END
4008
4009
4010JVM_ENTRY(jobjectArray, JVM_GetClassMethods(JNIEnv *env, jclass cls, jint which))
4011  JVMWrapper("JVM_GetClassMethods");
4012  JvmtiVMObjectAllocEventCollector oam;
4013  oop mirror = JNIHandles::resolve_non_null(cls);
4014  objArrayOop result = Reflection::reflect_methods(mirror, which, CHECK_NULL);
4015  //%note jvm_r4
4016  return (jobjectArray) JNIHandles::make_local(env, result);
4017JVM_END
4018
4019
4020JVM_ENTRY(jobjectArray, JVM_GetClassConstructors(JNIEnv *env, jclass cls, jint which))
4021  JVMWrapper("JVM_GetClassConstructors");
4022  JvmtiVMObjectAllocEventCollector oam;
4023  oop mirror = JNIHandles::resolve_non_null(cls);
4024  objArrayOop result = Reflection::reflect_constructors(mirror, which, CHECK_NULL);
4025  //%note jvm_r4
4026  return (jobjectArray) JNIHandles::make_local(env, result);
4027JVM_END
4028
4029
4030JVM_ENTRY(jobject, JVM_GetClassField(JNIEnv *env, jclass cls, jstring name, jint which))
4031  JVMWrapper("JVM_GetClassField");
4032  JvmtiVMObjectAllocEventCollector oam;
4033  if (name == NULL) return NULL;
4034  Handle str (THREAD, JNIHandles::resolve_non_null(name));
4035
4036  const char* cstr = java_lang_String::as_utf8_string(str());
4037  symbolHandle field_name =
4038           symbolHandle(THREAD, SymbolTable::probe(cstr, (int)strlen(cstr)));
4039  if (field_name.is_null()) {
4040    THROW_0(vmSymbols::java_lang_NoSuchFieldException());
4041  }
4042
4043  oop mirror = JNIHandles::resolve_non_null(cls);
4044  oop result = Reflection::reflect_field(mirror, field_name(), which, CHECK_NULL);
4045  if (result == NULL) {
4046    THROW_0(vmSymbols::java_lang_NoSuchFieldException());
4047  }
4048  return JNIHandles::make_local(env, result);
4049JVM_END
4050
4051
4052JVM_ENTRY(jobject, JVM_GetClassMethod(JNIEnv *env, jclass cls, jstring name, jobjectArray types, jint which))
4053  JVMWrapper("JVM_GetClassMethod");
4054  JvmtiVMObjectAllocEventCollector oam;
4055  if (name == NULL) {
4056    THROW_0(vmSymbols::java_lang_NullPointerException());
4057  }
4058  Handle str (THREAD, JNIHandles::resolve_non_null(name));
4059
4060  const char* cstr = java_lang_String::as_utf8_string(str());
4061  symbolHandle method_name =
4062          symbolHandle(THREAD, SymbolTable::probe(cstr, (int)strlen(cstr)));
4063  if (method_name.is_null()) {
4064    THROW_0(vmSymbols::java_lang_NoSuchMethodException());
4065  }
4066
4067  oop mirror = JNIHandles::resolve_non_null(cls);
4068  objArrayHandle tarray (THREAD, objArrayOop(JNIHandles::resolve(types)));
4069  oop result = Reflection::reflect_method(mirror, method_name, tarray,
4070                                          which, CHECK_NULL);
4071  if (result == NULL) {
4072    THROW_0(vmSymbols::java_lang_NoSuchMethodException());
4073  }
4074  return JNIHandles::make_local(env, result);
4075JVM_END
4076
4077
4078JVM_ENTRY(jobject, JVM_GetClassConstructor(JNIEnv *env, jclass cls, jobjectArray types, jint which))
4079  JVMWrapper("JVM_GetClassConstructor");
4080  JvmtiVMObjectAllocEventCollector oam;
4081  oop mirror = JNIHandles::resolve_non_null(cls);
4082  objArrayHandle tarray (THREAD, objArrayOop(JNIHandles::resolve(types)));
4083  oop result = Reflection::reflect_constructor(mirror, tarray, which, CHECK_NULL);
4084  if (result == NULL) {
4085    THROW_0(vmSymbols::java_lang_NoSuchMethodException());
4086  }
4087  return (jobject) JNIHandles::make_local(env, result);
4088JVM_END
4089
4090
4091// Instantiation ///////////////////////////////////////////////////////////////////////////////
4092
4093JVM_ENTRY(jobject, JVM_NewInstance(JNIEnv *env, jclass cls))
4094  JVMWrapper("JVM_NewInstance");
4095  Handle mirror(THREAD, JNIHandles::resolve_non_null(cls));
4096
4097  methodOop resolved_constructor = java_lang_Class::resolved_constructor(mirror());
4098  if (resolved_constructor == NULL) {
4099    klassOop k = java_lang_Class::as_klassOop(mirror());
4100    // The java.lang.Class object caches a resolved constructor if all the checks
4101    // below were done successfully and a constructor was found.
4102
4103    // Do class based checks
4104    if (java_lang_Class::is_primitive(mirror())) {
4105      const char* msg = "";
4106      if      (mirror == Universe::bool_mirror())   msg = "java/lang/Boolean";
4107      else if (mirror == Universe::char_mirror())   msg = "java/lang/Character";
4108      else if (mirror == Universe::float_mirror())  msg = "java/lang/Float";
4109      else if (mirror == Universe::double_mirror()) msg = "java/lang/Double";
4110      else if (mirror == Universe::byte_mirror())   msg = "java/lang/Byte";
4111      else if (mirror == Universe::short_mirror())  msg = "java/lang/Short";
4112      else if (mirror == Universe::int_mirror())    msg = "java/lang/Integer";
4113      else if (mirror == Universe::long_mirror())   msg = "java/lang/Long";
4114      THROW_MSG_0(vmSymbols::java_lang_NullPointerException(), msg);
4115    }
4116
4117    // Check whether we are allowed to instantiate this class
4118    Klass::cast(k)->check_valid_for_instantiation(false, CHECK_NULL); // Array classes get caught here
4119    instanceKlassHandle klass(THREAD, k);
4120    // Make sure class is initialized (also so all methods are rewritten)
4121    klass->initialize(CHECK_NULL);
4122
4123    // Lookup default constructor
4124    resolved_constructor = klass->find_method(vmSymbols::object_initializer_name(), vmSymbols::void_method_signature());
4125    if (resolved_constructor == NULL) {
4126      ResourceMark rm(THREAD);
4127      THROW_MSG_0(vmSymbols::java_lang_InstantiationException(), klass->external_name());
4128    }
4129
4130    // Cache result in java.lang.Class object. Does not have to be MT safe.
4131    java_lang_Class::set_resolved_constructor(mirror(), resolved_constructor);
4132  }
4133
4134  assert(resolved_constructor != NULL, "sanity check");
4135  methodHandle constructor = methodHandle(THREAD, resolved_constructor);
4136
4137  // We have an initialized instanceKlass with a default constructor
4138  instanceKlassHandle klass(THREAD, java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls)));
4139  assert(klass->is_initialized() || klass->is_being_initialized(), "sanity check");
4140
4141  // Do security check
4142  klassOop caller_klass = NULL;
4143  if (UsePrivilegedStack) {
4144    caller_klass = thread->security_get_caller_class(2);
4145
4146    if (!Reflection::verify_class_access(caller_klass, klass(), false) ||
4147        !Reflection::verify_field_access(caller_klass,
4148                                         klass(),
4149                                         klass(),
4150                                         constructor->access_flags(),
4151                                         false,
4152                                         true)) {
4153      ResourceMark rm(THREAD);
4154      THROW_MSG_0(vmSymbols::java_lang_IllegalAccessException(), klass->external_name());
4155    }
4156  }
4157
4158  // Allocate object and call constructor
4159  Handle receiver = klass->allocate_instance_handle(CHECK_NULL);
4160  JavaCalls::call_default_constructor(thread, constructor, receiver, CHECK_NULL);
4161
4162  jobject res = JNIHandles::make_local(env, receiver());
4163  if (JvmtiExport::should_post_vm_object_alloc()) {
4164    JvmtiExport::post_vm_object_alloc(JavaThread::current(), receiver());
4165  }
4166  return res;
4167JVM_END
4168
4169
4170// Field ////////////////////////////////////////////////////////////////////////////////////////////
4171
4172JVM_ENTRY(jobject, JVM_GetField(JNIEnv *env, jobject field, jobject obj))
4173  JVMWrapper("JVM_GetField");
4174  JvmtiVMObjectAllocEventCollector oam;
4175  Handle field_mirror(thread, JNIHandles::resolve(field));
4176  Handle receiver    (thread, JNIHandles::resolve(obj));
4177  fieldDescriptor fd;
4178  Reflection::resolve_field(field_mirror, receiver, &fd, false, CHECK_NULL);
4179  jvalue value;
4180  BasicType type = Reflection::field_get(&value, &fd, receiver);
4181  oop box = Reflection::box(&value, type, CHECK_NULL);
4182  return JNIHandles::make_local(env, box);
4183JVM_END
4184
4185
4186JVM_ENTRY(jvalue, JVM_GetPrimitiveField(JNIEnv *env, jobject field, jobject obj, unsigned char wCode))
4187  JVMWrapper("JVM_GetPrimitiveField");
4188  Handle field_mirror(thread, JNIHandles::resolve(field));
4189  Handle receiver    (thread, JNIHandles::resolve(obj));
4190  fieldDescriptor fd;
4191  jvalue value;
4192  value.j = 0;
4193  Reflection::resolve_field(field_mirror, receiver, &fd, false, CHECK_(value));
4194  BasicType type = Reflection::field_get(&value, &fd, receiver);
4195  BasicType wide_type = (BasicType) wCode;
4196  if (type != wide_type) {
4197    Reflection::widen(&value, type, wide_type, CHECK_(value));
4198  }
4199  return value;
4200JVM_END // should really be JVM_END, but that doesn't work for union types!
4201
4202
4203JVM_ENTRY(void, JVM_SetField(JNIEnv *env, jobject field, jobject obj, jobject val))
4204  JVMWrapper("JVM_SetField");
4205  Handle field_mirror(thread, JNIHandles::resolve(field));
4206  Handle receiver    (thread, JNIHandles::resolve(obj));
4207  oop box = JNIHandles::resolve(val);
4208  fieldDescriptor fd;
4209  Reflection::resolve_field(field_mirror, receiver, &fd, true, CHECK);
4210  BasicType field_type = fd.field_type();
4211  jvalue value;
4212  BasicType value_type;
4213  if (field_type == T_OBJECT || field_type == T_ARRAY) {
4214    // Make sure we do no unbox e.g. java/lang/Integer instances when storing into an object array
4215    value_type = Reflection::unbox_for_regular_object(box, &value);
4216    Reflection::field_set(&value, &fd, receiver, field_type, CHECK);
4217  } else {
4218    value_type = Reflection::unbox_for_primitive(box, &value, CHECK);
4219    Reflection::field_set(&value, &fd, receiver, value_type, CHECK);
4220  }
4221JVM_END
4222
4223
4224JVM_ENTRY(void, JVM_SetPrimitiveField(JNIEnv *env, jobject field, jobject obj, jvalue v, unsigned char vCode))
4225  JVMWrapper("JVM_SetPrimitiveField");
4226  Handle field_mirror(thread, JNIHandles::resolve(field));
4227  Handle receiver    (thread, JNIHandles::resolve(obj));
4228  fieldDescriptor fd;
4229  Reflection::resolve_field(field_mirror, receiver, &fd, true, CHECK);
4230  BasicType value_type = (BasicType) vCode;
4231  Reflection::field_set(&v, &fd, receiver, value_type, CHECK);
4232JVM_END
4233
4234
4235// Method ///////////////////////////////////////////////////////////////////////////////////////////
4236
4237JVM_ENTRY(jobject, JVM_InvokeMethod(JNIEnv *env, jobject method, jobject obj, jobjectArray args0))
4238  JVMWrapper("JVM_InvokeMethod");
4239  Handle method_handle;
4240  if (thread->stack_available((address) &method_handle) >= JVMInvokeMethodSlack) {
4241    method_handle = Handle(THREAD, JNIHandles::resolve(method));
4242    Handle receiver(THREAD, JNIHandles::resolve(obj));
4243    objArrayHandle args(THREAD, objArrayOop(JNIHandles::resolve(args0)));
4244    oop result = Reflection::invoke_method(method_handle(), receiver, args, CHECK_NULL);
4245    jobject res = JNIHandles::make_local(env, result);
4246    if (JvmtiExport::should_post_vm_object_alloc()) {
4247      oop ret_type = java_lang_reflect_Method::return_type(method_handle());
4248      assert(ret_type != NULL, "sanity check: ret_type oop must not be NULL!");
4249      if (java_lang_Class::is_primitive(ret_type)) {
4250        // Only for primitive type vm allocates memory for java object.
4251        // See box() method.
4252        JvmtiExport::post_vm_object_alloc(JavaThread::current(), result);
4253      }
4254    }
4255    return res;
4256  } else {
4257    THROW_0(vmSymbols::java_lang_StackOverflowError());
4258  }
4259JVM_END
4260
4261
4262JVM_ENTRY(jobject, JVM_NewInstanceFromConstructor(JNIEnv *env, jobject c, jobjectArray args0))
4263  JVMWrapper("JVM_NewInstanceFromConstructor");
4264  oop constructor_mirror = JNIHandles::resolve(c);
4265  objArrayHandle args(THREAD, objArrayOop(JNIHandles::resolve(args0)));
4266  oop result = Reflection::invoke_constructor(constructor_mirror, args, CHECK_NULL);
4267  jobject res = JNIHandles::make_local(env, result);
4268  if (JvmtiExport::should_post_vm_object_alloc()) {
4269    JvmtiExport::post_vm_object_alloc(JavaThread::current(), result);
4270  }
4271  return res;
4272JVM_END
4273
4274#endif /* SUPPORT_OLD_REFLECTION */
4275
4276// Atomic ///////////////////////////////////////////////////////////////////////////////////////////
4277
4278JVM_LEAF(jboolean, JVM_SupportsCX8())
4279  JVMWrapper("JVM_SupportsCX8");
4280  return VM_Version::supports_cx8();
4281JVM_END
4282
4283
4284JVM_ENTRY(jboolean, JVM_CX8Field(JNIEnv *env, jobject obj, jfieldID fid, jlong oldVal, jlong newVal))
4285  JVMWrapper("JVM_CX8Field");
4286  jlong res;
4287  oop             o       = JNIHandles::resolve(obj);
4288  intptr_t        fldOffs = jfieldIDWorkaround::from_instance_jfieldID(o->klass(), fid);
4289  volatile jlong* addr    = (volatile jlong*)((address)o + fldOffs);
4290
4291  assert(VM_Version::supports_cx8(), "cx8 not supported");
4292  res = Atomic::cmpxchg(newVal, addr, oldVal);
4293
4294  return res == oldVal;
4295JVM_END
4296
4297// DTrace ///////////////////////////////////////////////////////////////////
4298
4299JVM_ENTRY(jint, JVM_DTraceGetVersion(JNIEnv* env))
4300  JVMWrapper("JVM_DTraceGetVersion");
4301  return (jint)JVM_TRACING_DTRACE_VERSION;
4302JVM_END
4303
4304JVM_ENTRY(jlong,JVM_DTraceActivate(
4305    JNIEnv* env, jint version, jstring module_name, jint providers_count,
4306    JVM_DTraceProvider* providers))
4307  JVMWrapper("JVM_DTraceActivate");
4308  return DTraceJSDT::activate(
4309    version, module_name, providers_count, providers, CHECK_0);
4310JVM_END
4311
4312JVM_ENTRY(jboolean,JVM_DTraceIsProbeEnabled(JNIEnv* env, jmethodID method))
4313  JVMWrapper("JVM_DTraceIsProbeEnabled");
4314  return DTraceJSDT::is_probe_enabled(method);
4315JVM_END
4316
4317JVM_ENTRY(void,JVM_DTraceDispose(JNIEnv* env, jlong handle))
4318  JVMWrapper("JVM_DTraceDispose");
4319  DTraceJSDT::dispose(handle);
4320JVM_END
4321
4322JVM_ENTRY(jboolean,JVM_DTraceIsSupported(JNIEnv* env))
4323  JVMWrapper("JVM_DTraceIsSupported");
4324  return DTraceJSDT::is_supported();
4325JVM_END
4326
4327// Returns an array of all live Thread objects (VM internal JavaThreads,
4328// jvmti agent threads, and JNI attaching threads  are skipped)
4329// See CR 6404306 regarding JNI attaching threads
4330JVM_ENTRY(jobjectArray, JVM_GetAllThreads(JNIEnv *env, jclass dummy))
4331  ResourceMark rm(THREAD);
4332  ThreadsListEnumerator tle(THREAD, false, false);
4333  JvmtiVMObjectAllocEventCollector oam;
4334
4335  int num_threads = tle.num_threads();
4336  objArrayOop r = oopFactory::new_objArray(SystemDictionary::Thread_klass(), num_threads, CHECK_NULL);
4337  objArrayHandle threads_ah(THREAD, r);
4338
4339  for (int i = 0; i < num_threads; i++) {
4340    Handle h = tle.get_threadObj(i);
4341    threads_ah->obj_at_put(i, h());
4342  }
4343
4344  return (jobjectArray) JNIHandles::make_local(env, threads_ah());
4345JVM_END
4346
4347
4348// Support for java.lang.Thread.getStackTrace() and getAllStackTraces() methods
4349// Return StackTraceElement[][], each element is the stack trace of a thread in
4350// the corresponding entry in the given threads array
4351JVM_ENTRY(jobjectArray, JVM_DumpThreads(JNIEnv *env, jclass threadClass, jobjectArray threads))
4352  JVMWrapper("JVM_DumpThreads");
4353  JvmtiVMObjectAllocEventCollector oam;
4354
4355  // Check if threads is null
4356  if (threads == NULL) {
4357    THROW_(vmSymbols::java_lang_NullPointerException(), 0);
4358  }
4359
4360  objArrayOop a = objArrayOop(JNIHandles::resolve_non_null(threads));
4361  objArrayHandle ah(THREAD, a);
4362  int num_threads = ah->length();
4363  // check if threads is non-empty array
4364  if (num_threads == 0) {
4365    THROW_(vmSymbols::java_lang_IllegalArgumentException(), 0);
4366  }
4367
4368  // check if threads is not an array of objects of Thread class
4369  klassOop k = objArrayKlass::cast(ah->klass())->element_klass();
4370  if (k != SystemDictionary::Thread_klass()) {
4371    THROW_(vmSymbols::java_lang_IllegalArgumentException(), 0);
4372  }
4373
4374  ResourceMark rm(THREAD);
4375
4376  GrowableArray<instanceHandle>* thread_handle_array = new GrowableArray<instanceHandle>(num_threads);
4377  for (int i = 0; i < num_threads; i++) {
4378    oop thread_obj = ah->obj_at(i);
4379    instanceHandle h(THREAD, (instanceOop) thread_obj);
4380    thread_handle_array->append(h);
4381  }
4382
4383  Handle stacktraces = ThreadService::dump_stack_traces(thread_handle_array, num_threads, CHECK_NULL);
4384  return (jobjectArray)JNIHandles::make_local(env, stacktraces());
4385
4386JVM_END
4387
4388// JVM monitoring and management support
4389JVM_ENTRY_NO_ENV(void*, JVM_GetManagement(jint version))
4390  return Management::get_jmm_interface(version);
4391JVM_END
4392
4393// com.sun.tools.attach.VirtualMachine agent properties support
4394//
4395// Initialize the agent properties with the properties maintained in the VM
4396JVM_ENTRY(jobject, JVM_InitAgentProperties(JNIEnv *env, jobject properties))
4397  JVMWrapper("JVM_InitAgentProperties");
4398  ResourceMark rm;
4399
4400  Handle props(THREAD, JNIHandles::resolve_non_null(properties));
4401
4402  PUTPROP(props, "sun.java.command", Arguments::java_command());
4403  PUTPROP(props, "sun.jvm.flags", Arguments::jvm_flags());
4404  PUTPROP(props, "sun.jvm.args", Arguments::jvm_args());
4405  return properties;
4406JVM_END
4407
4408JVM_ENTRY(jobjectArray, JVM_GetEnclosingMethodInfo(JNIEnv *env, jclass ofClass))
4409{
4410  JVMWrapper("JVM_GetEnclosingMethodInfo");
4411  JvmtiVMObjectAllocEventCollector oam;
4412
4413  if (ofClass == NULL) {
4414    return NULL;
4415  }
4416  Handle mirror(THREAD, JNIHandles::resolve_non_null(ofClass));
4417  // Special handling for primitive objects
4418  if (java_lang_Class::is_primitive(mirror())) {
4419    return NULL;
4420  }
4421  klassOop k = java_lang_Class::as_klassOop(mirror());
4422  if (!Klass::cast(k)->oop_is_instance()) {
4423    return NULL;
4424  }
4425  instanceKlassHandle ik_h(THREAD, k);
4426  int encl_method_class_idx = ik_h->enclosing_method_class_index();
4427  if (encl_method_class_idx == 0) {
4428    return NULL;
4429  }
4430  objArrayOop dest_o = oopFactory::new_objArray(SystemDictionary::Object_klass(), 3, CHECK_NULL);
4431  objArrayHandle dest(THREAD, dest_o);
4432  klassOop enc_k = ik_h->constants()->klass_at(encl_method_class_idx, CHECK_NULL);
4433  dest->obj_at_put(0, Klass::cast(enc_k)->java_mirror());
4434  int encl_method_method_idx = ik_h->enclosing_method_method_index();
4435  if (encl_method_method_idx != 0) {
4436    symbolOop sym_o = ik_h->constants()->symbol_at(
4437                        extract_low_short_from_int(
4438                          ik_h->constants()->name_and_type_at(encl_method_method_idx)));
4439    symbolHandle sym(THREAD, sym_o);
4440    Handle str = java_lang_String::create_from_symbol(sym, CHECK_NULL);
4441    dest->obj_at_put(1, str());
4442    sym_o = ik_h->constants()->symbol_at(
4443              extract_high_short_from_int(
4444                ik_h->constants()->name_and_type_at(encl_method_method_idx)));
4445    sym = symbolHandle(THREAD, sym_o);
4446    str = java_lang_String::create_from_symbol(sym, CHECK_NULL);
4447    dest->obj_at_put(2, str());
4448  }
4449  return (jobjectArray) JNIHandles::make_local(dest());
4450}
4451JVM_END
4452
4453JVM_ENTRY(jintArray, JVM_GetThreadStateValues(JNIEnv* env,
4454                                              jint javaThreadState))
4455{
4456  // If new thread states are added in future JDK and VM versions,
4457  // this should check if the JDK version is compatible with thread
4458  // states supported by the VM.  Return NULL if not compatible.
4459  //
4460  // This function must map the VM java_lang_Thread::ThreadStatus
4461  // to the Java thread state that the JDK supports.
4462  //
4463
4464  typeArrayHandle values_h;
4465  switch (javaThreadState) {
4466    case JAVA_THREAD_STATE_NEW : {
4467      typeArrayOop r = oopFactory::new_typeArray(T_INT, 1, CHECK_NULL);
4468      values_h = typeArrayHandle(THREAD, r);
4469      values_h->int_at_put(0, java_lang_Thread::NEW);
4470      break;
4471    }
4472    case JAVA_THREAD_STATE_RUNNABLE : {
4473      typeArrayOop r = oopFactory::new_typeArray(T_INT, 1, CHECK_NULL);
4474      values_h = typeArrayHandle(THREAD, r);
4475      values_h->int_at_put(0, java_lang_Thread::RUNNABLE);
4476      break;
4477    }
4478    case JAVA_THREAD_STATE_BLOCKED : {
4479      typeArrayOop r = oopFactory::new_typeArray(T_INT, 1, CHECK_NULL);
4480      values_h = typeArrayHandle(THREAD, r);
4481      values_h->int_at_put(0, java_lang_Thread::BLOCKED_ON_MONITOR_ENTER);
4482      break;
4483    }
4484    case JAVA_THREAD_STATE_WAITING : {
4485      typeArrayOop r = oopFactory::new_typeArray(T_INT, 2, CHECK_NULL);
4486      values_h = typeArrayHandle(THREAD, r);
4487      values_h->int_at_put(0, java_lang_Thread::IN_OBJECT_WAIT);
4488      values_h->int_at_put(1, java_lang_Thread::PARKED);
4489      break;
4490    }
4491    case JAVA_THREAD_STATE_TIMED_WAITING : {
4492      typeArrayOop r = oopFactory::new_typeArray(T_INT, 3, CHECK_NULL);
4493      values_h = typeArrayHandle(THREAD, r);
4494      values_h->int_at_put(0, java_lang_Thread::SLEEPING);
4495      values_h->int_at_put(1, java_lang_Thread::IN_OBJECT_WAIT_TIMED);
4496      values_h->int_at_put(2, java_lang_Thread::PARKED_TIMED);
4497      break;
4498    }
4499    case JAVA_THREAD_STATE_TERMINATED : {
4500      typeArrayOop r = oopFactory::new_typeArray(T_INT, 1, CHECK_NULL);
4501      values_h = typeArrayHandle(THREAD, r);
4502      values_h->int_at_put(0, java_lang_Thread::TERMINATED);
4503      break;
4504    }
4505    default:
4506      // Unknown state - probably incompatible JDK version
4507      return NULL;
4508  }
4509
4510  return (jintArray) JNIHandles::make_local(env, values_h());
4511}
4512JVM_END
4513
4514
4515JVM_ENTRY(jobjectArray, JVM_GetThreadStateNames(JNIEnv* env,
4516                                                jint javaThreadState,
4517                                                jintArray values))
4518{
4519  // If new thread states are added in future JDK and VM versions,
4520  // this should check if the JDK version is compatible with thread
4521  // states supported by the VM.  Return NULL if not compatible.
4522  //
4523  // This function must map the VM java_lang_Thread::ThreadStatus
4524  // to the Java thread state that the JDK supports.
4525  //
4526
4527  ResourceMark rm;
4528
4529  // Check if threads is null
4530  if (values == NULL) {
4531    THROW_(vmSymbols::java_lang_NullPointerException(), 0);
4532  }
4533
4534  typeArrayOop v = typeArrayOop(JNIHandles::resolve_non_null(values));
4535  typeArrayHandle values_h(THREAD, v);
4536
4537  objArrayHandle names_h;
4538  switch (javaThreadState) {
4539    case JAVA_THREAD_STATE_NEW : {
4540      assert(values_h->length() == 1 &&
4541               values_h->int_at(0) == java_lang_Thread::NEW,
4542             "Invalid threadStatus value");
4543
4544      objArrayOop r = oopFactory::new_objArray(SystemDictionary::String_klass(),
4545                                               1, /* only 1 substate */
4546                                               CHECK_NULL);
4547      names_h = objArrayHandle(THREAD, r);
4548      Handle name = java_lang_String::create_from_str("NEW", CHECK_NULL);
4549      names_h->obj_at_put(0, name());
4550      break;
4551    }
4552    case JAVA_THREAD_STATE_RUNNABLE : {
4553      assert(values_h->length() == 1 &&
4554               values_h->int_at(0) == java_lang_Thread::RUNNABLE,
4555             "Invalid threadStatus value");
4556
4557      objArrayOop r = oopFactory::new_objArray(SystemDictionary::String_klass(),
4558                                               1, /* only 1 substate */
4559                                               CHECK_NULL);
4560      names_h = objArrayHandle(THREAD, r);
4561      Handle name = java_lang_String::create_from_str("RUNNABLE", CHECK_NULL);
4562      names_h->obj_at_put(0, name());
4563      break;
4564    }
4565    case JAVA_THREAD_STATE_BLOCKED : {
4566      assert(values_h->length() == 1 &&
4567               values_h->int_at(0) == java_lang_Thread::BLOCKED_ON_MONITOR_ENTER,
4568             "Invalid threadStatus value");
4569
4570      objArrayOop r = oopFactory::new_objArray(SystemDictionary::String_klass(),
4571                                               1, /* only 1 substate */
4572                                               CHECK_NULL);
4573      names_h = objArrayHandle(THREAD, r);
4574      Handle name = java_lang_String::create_from_str("BLOCKED", CHECK_NULL);
4575      names_h->obj_at_put(0, name());
4576      break;
4577    }
4578    case JAVA_THREAD_STATE_WAITING : {
4579      assert(values_h->length() == 2 &&
4580               values_h->int_at(0) == java_lang_Thread::IN_OBJECT_WAIT &&
4581               values_h->int_at(1) == java_lang_Thread::PARKED,
4582             "Invalid threadStatus value");
4583      objArrayOop r = oopFactory::new_objArray(SystemDictionary::String_klass(),
4584                                               2, /* number of substates */
4585                                               CHECK_NULL);
4586      names_h = objArrayHandle(THREAD, r);
4587      Handle name0 = java_lang_String::create_from_str("WAITING.OBJECT_WAIT",
4588                                                       CHECK_NULL);
4589      Handle name1 = java_lang_String::create_from_str("WAITING.PARKED",
4590                                                       CHECK_NULL);
4591      names_h->obj_at_put(0, name0());
4592      names_h->obj_at_put(1, name1());
4593      break;
4594    }
4595    case JAVA_THREAD_STATE_TIMED_WAITING : {
4596      assert(values_h->length() == 3 &&
4597               values_h->int_at(0) == java_lang_Thread::SLEEPING &&
4598               values_h->int_at(1) == java_lang_Thread::IN_OBJECT_WAIT_TIMED &&
4599               values_h->int_at(2) == java_lang_Thread::PARKED_TIMED,
4600             "Invalid threadStatus value");
4601      objArrayOop r = oopFactory::new_objArray(SystemDictionary::String_klass(),
4602                                               3, /* number of substates */
4603                                               CHECK_NULL);
4604      names_h = objArrayHandle(THREAD, r);
4605      Handle name0 = java_lang_String::create_from_str("TIMED_WAITING.SLEEPING",
4606                                                       CHECK_NULL);
4607      Handle name1 = java_lang_String::create_from_str("TIMED_WAITING.OBJECT_WAIT",
4608                                                       CHECK_NULL);
4609      Handle name2 = java_lang_String::create_from_str("TIMED_WAITING.PARKED",
4610                                                       CHECK_NULL);
4611      names_h->obj_at_put(0, name0());
4612      names_h->obj_at_put(1, name1());
4613      names_h->obj_at_put(2, name2());
4614      break;
4615    }
4616    case JAVA_THREAD_STATE_TERMINATED : {
4617      assert(values_h->length() == 1 &&
4618               values_h->int_at(0) == java_lang_Thread::TERMINATED,
4619             "Invalid threadStatus value");
4620      objArrayOop r = oopFactory::new_objArray(SystemDictionary::String_klass(),
4621                                               1, /* only 1 substate */
4622                                               CHECK_NULL);
4623      names_h = objArrayHandle(THREAD, r);
4624      Handle name = java_lang_String::create_from_str("TERMINATED", CHECK_NULL);
4625      names_h->obj_at_put(0, name());
4626      break;
4627    }
4628    default:
4629      // Unknown state - probably incompatible JDK version
4630      return NULL;
4631  }
4632  return (jobjectArray) JNIHandles::make_local(env, names_h());
4633}
4634JVM_END
4635
4636JVM_ENTRY(void, JVM_GetVersionInfo(JNIEnv* env, jvm_version_info* info, size_t info_size))
4637{
4638  memset(info, 0, sizeof(info_size));
4639
4640  info->jvm_version = Abstract_VM_Version::jvm_version();
4641  info->update_version = 0;          /* 0 in HotSpot Express VM */
4642  info->special_update_version = 0;  /* 0 in HotSpot Express VM */
4643
4644  // when we add a new capability in the jvm_version_info struct, we should also
4645  // consider to expose this new capability in the sun.rt.jvmCapabilities jvmstat
4646  // counter defined in runtimeService.cpp.
4647  info->is_attachable = AttachListener::is_attach_supported();
4648#ifdef KERNEL
4649  info->is_kernel_jvm = 1; // true;
4650#else  // KERNEL
4651  info->is_kernel_jvm = 0; // false;
4652#endif // KERNEL
4653}
4654JVM_END
4655