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