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