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