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