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