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