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(jclass, JVM_GetCallerClass(JNIEnv* env))
 727   JVMWrapper("JVM_GetCallerClass");
 728 
 729   // Getting the class of the caller frame.
 730   //
 731   // The call stack at this point looks something like this:
 732   //
 733   // [0] [ @CallerSensitive public sun.reflect.Reflection.getCallerClass ]
 734   // [1] [ @CallerSensitive API.method                                   ]
 735   // [.] [ (skipped intermediate frames)                                 ]
 736   // [n] [ caller                                                        ]
 737   vframeStream vfst(thread);
 738   // Cf. LibraryCallKit::inline_native_Reflection_getCallerClass
 739   for (int n = 0; !vfst.at_end(); vfst.security_next(), n++) {
 740     Method* m = vfst.method();
 741     assert(m != NULL, "sanity");
 742     switch (n) {
 743     case 0:
 744       // This must only be called from Reflection.getCallerClass
 745       if (m->intrinsic_id() != vmIntrinsics::_getCallerClass) {
 746         THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), "JVM_GetCallerClass must only be called from Reflection.getCallerClass");
 747       }
 748       // fall-through
 749     case 1:
 750       // Frame 0 and 1 must be caller sensitive.
 751       if (!m->caller_sensitive()) {
 752         THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), err_msg("CallerSensitive annotation expected at frame %d", n));
 753       }
 754       break;
 755     default:
 756       if (!m->is_ignored_by_security_stack_walk()) {
 757         // We have reached the desired frame; return the holder class.
 758         return (jclass) JNIHandles::make_local(env, m->method_holder()->java_mirror());
 759       }
 760       break;
 761     }
 762   }
 763   return NULL;
 764 JVM_END
 765 
 766 
 767 JVM_ENTRY(jclass, JVM_FindPrimitiveClass(JNIEnv* env, const char* utf))
 768   JVMWrapper("JVM_FindPrimitiveClass");
 769   oop mirror = NULL;
 770   BasicType t = name2type(utf);
 771   if (t != T_ILLEGAL && t != T_OBJECT && t != T_ARRAY) {
 772     mirror = Universe::java_mirror(t);
 773   }
 774   if (mirror == NULL) {
 775     THROW_MSG_0(vmSymbols::java_lang_ClassNotFoundException(), (char*) utf);
 776   } else {
 777     return (jclass) JNIHandles::make_local(env, mirror);
 778   }
 779 JVM_END
 780 
 781 
 782 // Returns a class loaded by the bootstrap class loader; or null
 783 // if not found.  ClassNotFoundException is not thrown.
 784 // FindClassFromBootLoader is exported to the launcher for windows.
 785 JVM_ENTRY(jclass, JVM_FindClassFromBootLoader(JNIEnv* env,
 786                                               const char* name))
 787   JVMWrapper("JVM_FindClassFromBootLoader");
 788 
 789   // Java libraries should ensure that name is never null...
 790   if (name == NULL || (int)strlen(name) > Symbol::max_length()) {
 791     // It's impossible to create this class;  the name cannot fit
 792     // into the constant pool.
 793     return NULL;
 794   }
 795 
 796   TempNewSymbol h_name = SymbolTable::new_symbol(name);
 797   Klass* k = SystemDictionary::resolve_or_null(h_name, CHECK_NULL);
 798   if (k == NULL) {
 799     return NULL;
 800   }
 801 
 802   if (log_is_enabled(Debug, class, resolve)) {
 803     trace_class_resolution(k);
 804   }
 805   return (jclass) JNIHandles::make_local(env, k->java_mirror());
 806 JVM_END
 807 
 808 // Find a class with this name in this loader, using the caller's protection domain.
 809 JVM_ENTRY(jclass, JVM_FindClassFromCaller(JNIEnv* env, const char* name,
 810                                           jboolean init, jobject loader,
 811                                           jclass caller))
 812   JVMWrapper("JVM_FindClassFromCaller throws ClassNotFoundException");
 813   // Java libraries should ensure that name is never null...
 814   if (name == NULL || (int)strlen(name) > Symbol::max_length()) {
 815     // It's impossible to create this class;  the name cannot fit
 816     // into the constant pool.
 817     THROW_MSG_0(vmSymbols::java_lang_ClassNotFoundException(), name);
 818   }
 819 
 820   TempNewSymbol h_name = SymbolTable::new_symbol(name);
 821 
 822   oop loader_oop = JNIHandles::resolve(loader);
 823   oop from_class = JNIHandles::resolve(caller);
 824   oop protection_domain = NULL;
 825   // If loader is null, shouldn't call ClassLoader.checkPackageAccess; otherwise get
 826   // NPE. Put it in another way, the bootstrap class loader has all permission and
 827   // thus no checkPackageAccess equivalence in the VM class loader.
 828   // The caller is also passed as NULL by the java code if there is no security
 829   // manager to avoid the performance cost of getting the calling class.
 830   if (from_class != NULL && loader_oop != NULL) {
 831     protection_domain = java_lang_Class::as_Klass(from_class)->protection_domain();
 832   }
 833 
 834   Handle h_loader(THREAD, loader_oop);
 835   Handle h_prot(THREAD, protection_domain);
 836   jclass result = find_class_from_class_loader(env, h_name, init, h_loader,
 837                                                h_prot, false, THREAD);
 838 
 839   if (log_is_enabled(Debug, class, resolve) && result != NULL) {
 840     trace_class_resolution(java_lang_Class::as_Klass(JNIHandles::resolve_non_null(result)));
 841   }
 842   return result;
 843 JVM_END
 844 
 845 // Currently only called from the old verifier.
 846 JVM_ENTRY(jclass, JVM_FindClassFromClass(JNIEnv *env, const char *name,
 847                                          jboolean init, jclass from))
 848   JVMWrapper("JVM_FindClassFromClass");
 849   if (name == NULL) {
 850     THROW_MSG_0(vmSymbols::java_lang_NoClassDefFoundError(), "No class name given");
 851   }
 852   if ((int)strlen(name) > Symbol::max_length()) {
 853     // It's impossible to create this class;  the name cannot fit
 854     // into the constant pool.
 855     Exceptions::fthrow(THREAD_AND_LOCATION,
 856                        vmSymbols::java_lang_NoClassDefFoundError(),
 857                        "Class name exceeds maximum length of %d: %s",
 858                        Symbol::max_length(),
 859                        name);
 860     return 0;
 861   }
 862   TempNewSymbol h_name = SymbolTable::new_symbol(name);
 863   oop from_class_oop = JNIHandles::resolve(from);
 864   Klass* from_class = (from_class_oop == NULL)
 865                            ? (Klass*)NULL
 866                            : java_lang_Class::as_Klass(from_class_oop);
 867   oop class_loader = NULL;
 868   oop protection_domain = NULL;
 869   if (from_class != NULL) {
 870     class_loader = from_class->class_loader();
 871     protection_domain = from_class->protection_domain();
 872   }
 873   Handle h_loader(THREAD, class_loader);
 874   Handle h_prot  (THREAD, protection_domain);
 875   jclass result = find_class_from_class_loader(env, h_name, init, h_loader,
 876                                                h_prot, true, thread);
 877 
 878   if (log_is_enabled(Debug, class, resolve) && result != NULL) {
 879     // this function is generally only used for class loading during verification.
 880     ResourceMark rm;
 881     oop from_mirror = JNIHandles::resolve_non_null(from);
 882     Klass* from_class = java_lang_Class::as_Klass(from_mirror);
 883     const char * from_name = from_class->external_name();
 884 
 885     oop mirror = JNIHandles::resolve_non_null(result);
 886     Klass* to_class = java_lang_Class::as_Klass(mirror);
 887     const char * to = to_class->external_name();
 888     log_debug(class, resolve)("%s %s (verification)", from_name, to);
 889   }
 890 
 891   return result;
 892 JVM_END
 893 
 894 static void is_lock_held_by_thread(Handle loader, PerfCounter* counter, TRAPS) {
 895   if (loader.is_null()) {
 896     return;
 897   }
 898 
 899   // check whether the current caller thread holds the lock or not.
 900   // If not, increment the corresponding counter
 901   if (ObjectSynchronizer::query_lock_ownership((JavaThread*)THREAD, loader) !=
 902       ObjectSynchronizer::owner_self) {
 903     counter->inc();
 904   }
 905 }
 906 
 907 // common code for JVM_DefineClass() and JVM_DefineClassWithSource()
 908 static jclass jvm_define_class_common(JNIEnv *env, const char *name,
 909                                       jobject loader, const jbyte *buf,
 910                                       jsize len, jobject pd, const char *source,
 911                                       TRAPS) {
 912   if (source == NULL)  source = "__JVM_DefineClass__";
 913 
 914   assert(THREAD->is_Java_thread(), "must be a JavaThread");
 915   JavaThread* jt = (JavaThread*) THREAD;
 916 
 917   PerfClassTraceTime vmtimer(ClassLoader::perf_define_appclass_time(),
 918                              ClassLoader::perf_define_appclass_selftime(),
 919                              ClassLoader::perf_define_appclasses(),
 920                              jt->get_thread_stat()->perf_recursion_counts_addr(),
 921                              jt->get_thread_stat()->perf_timers_addr(),
 922                              PerfClassTraceTime::DEFINE_CLASS);
 923 
 924   if (UsePerfData) {
 925     ClassLoader::perf_app_classfile_bytes_read()->inc(len);
 926   }
 927 
 928   // Since exceptions can be thrown, class initialization can take place
 929   // if name is NULL no check for class name in .class stream has to be made.
 930   TempNewSymbol class_name = NULL;
 931   if (name != NULL) {
 932     const int str_len = (int)strlen(name);
 933     if (str_len > Symbol::max_length()) {
 934       // It's impossible to create this class;  the name cannot fit
 935       // into the constant pool.
 936       Exceptions::fthrow(THREAD_AND_LOCATION,
 937                          vmSymbols::java_lang_NoClassDefFoundError(),
 938                          "Class name exceeds maximum length of %d: %s",
 939                          Symbol::max_length(),
 940                          name);
 941       return 0;
 942     }
 943     class_name = SymbolTable::new_symbol(name, str_len);
 944   }
 945 
 946   ResourceMark rm(THREAD);
 947   ClassFileStream st((u1*)buf, len, source, ClassFileStream::verify);
 948   Handle class_loader (THREAD, JNIHandles::resolve(loader));
 949   if (UsePerfData) {
 950     is_lock_held_by_thread(class_loader,
 951                            ClassLoader::sync_JVMDefineClassLockFreeCounter(),
 952                            THREAD);
 953   }
 954   Handle protection_domain (THREAD, JNIHandles::resolve(pd));
 955   Klass* k = SystemDictionary::resolve_from_stream(class_name,
 956                                                    class_loader,
 957                                                    protection_domain,
 958                                                    &st,
 959                                                    CHECK_NULL);
 960 
 961   if (log_is_enabled(Debug, class, resolve) && k != NULL) {
 962     trace_class_resolution(k);
 963   }
 964 
 965   return (jclass) JNIHandles::make_local(env, k->java_mirror());
 966 }
 967 
 968 
 969 JVM_ENTRY(jclass, JVM_DefineClass(JNIEnv *env, const char *name, jobject loader, const jbyte *buf, jsize len, jobject pd))
 970   JVMWrapper("JVM_DefineClass");
 971 
 972   return jvm_define_class_common(env, name, loader, buf, len, pd, NULL, THREAD);
 973 JVM_END
 974 
 975 
 976 JVM_ENTRY(jclass, JVM_DefineClassWithSource(JNIEnv *env, const char *name, jobject loader, const jbyte *buf, jsize len, jobject pd, const char *source))
 977   JVMWrapper("JVM_DefineClassWithSource");
 978 
 979   return jvm_define_class_common(env, name, loader, buf, len, pd, source, THREAD);
 980 JVM_END
 981 
 982 JVM_ENTRY(jclass, JVM_FindLoadedClass(JNIEnv *env, jobject loader, jstring name))
 983   JVMWrapper("JVM_FindLoadedClass");
 984   ResourceMark rm(THREAD);
 985 
 986   Handle h_name (THREAD, JNIHandles::resolve_non_null(name));
 987   Handle string = java_lang_String::internalize_classname(h_name, CHECK_NULL);
 988 
 989   const char* str   = java_lang_String::as_utf8_string(string());
 990   // Sanity check, don't expect null
 991   if (str == NULL) return NULL;
 992 
 993   const int str_len = (int)strlen(str);
 994   if (str_len > Symbol::max_length()) {
 995     // It's impossible to create this class;  the name cannot fit
 996     // into the constant pool.
 997     return NULL;
 998   }
 999   TempNewSymbol klass_name = SymbolTable::new_symbol(str, str_len);
1000 
1001   // Security Note:
1002   //   The Java level wrapper will perform the necessary security check allowing
1003   //   us to pass the NULL as the initiating class loader.
1004   Handle h_loader(THREAD, JNIHandles::resolve(loader));
1005   if (UsePerfData) {
1006     is_lock_held_by_thread(h_loader,
1007                            ClassLoader::sync_JVMFindLoadedClassLockFreeCounter(),
1008                            THREAD);
1009   }
1010 
1011   Klass* k = SystemDictionary::find_instance_or_array_klass(klass_name,
1012                                                               h_loader,
1013                                                               Handle(),
1014                                                               CHECK_NULL);
1015 #if INCLUDE_CDS
1016   if (k == NULL) {
1017     // If the class is not already loaded, try to see if it's in the shared
1018     // archive for the current classloader (h_loader).
1019     k = SystemDictionaryShared::find_or_load_shared_class(klass_name, h_loader, CHECK_NULL);
1020   }
1021 #endif
1022   return (k == NULL) ? NULL :
1023             (jclass) JNIHandles::make_local(env, k->java_mirror());
1024 JVM_END
1025 
1026 // Module support //////////////////////////////////////////////////////////////////////////////
1027 
1028 JVM_ENTRY(void, JVM_DefineModule(JNIEnv *env, jobject module, jboolean is_open, jstring version,
1029                                  jstring location, const char* const* packages, jsize num_packages))
1030   JVMWrapper("JVM_DefineModule");
1031   Modules::define_module(module, is_open, version, location, packages, num_packages, CHECK);
1032 JVM_END
1033 
1034 JVM_ENTRY(void, JVM_SetBootLoaderUnnamedModule(JNIEnv *env, jobject module))
1035   JVMWrapper("JVM_SetBootLoaderUnnamedModule");
1036   Modules::set_bootloader_unnamed_module(module, CHECK);
1037 JVM_END
1038 
1039 JVM_ENTRY(void, JVM_AddModuleExports(JNIEnv *env, jobject from_module, const char* package, jobject to_module))
1040   JVMWrapper("JVM_AddModuleExports");
1041   Modules::add_module_exports_qualified(from_module, package, to_module, CHECK);
1042 JVM_END
1043 
1044 JVM_ENTRY(void, JVM_AddModuleExportsToAllUnnamed(JNIEnv *env, jobject from_module, const char* package))
1045   JVMWrapper("JVM_AddModuleExportsToAllUnnamed");
1046   Modules::add_module_exports_to_all_unnamed(from_module, package, CHECK);
1047 JVM_END
1048 
1049 JVM_ENTRY(void, JVM_AddModuleExportsToAll(JNIEnv *env, jobject from_module, const char* package))
1050   JVMWrapper("JVM_AddModuleExportsToAll");
1051   Modules::add_module_exports(from_module, package, NULL, CHECK);
1052 JVM_END
1053 
1054 JVM_ENTRY (void, JVM_AddReadsModule(JNIEnv *env, jobject from_module, jobject source_module))
1055   JVMWrapper("JVM_AddReadsModule");
1056   Modules::add_reads_module(from_module, source_module, CHECK);
1057 JVM_END
1058 
1059 // Reflection support //////////////////////////////////////////////////////////////////////////////
1060 
1061 JVM_ENTRY(jstring, JVM_InitClassName(JNIEnv *env, jclass cls))
1062   assert (cls != NULL, "illegal class");
1063   JVMWrapper("JVM_InitClassName");
1064   JvmtiVMObjectAllocEventCollector oam;
1065   ResourceMark rm(THREAD);
1066   HandleMark hm(THREAD);
1067   Handle java_class(THREAD, JNIHandles::resolve(cls));
1068   oop result = java_lang_Class::name(java_class, CHECK_NULL);
1069   return (jstring) JNIHandles::make_local(env, result);
1070 JVM_END
1071 
1072 
1073 JVM_ENTRY(jobjectArray, JVM_GetClassInterfaces(JNIEnv *env, jclass cls))
1074   JVMWrapper("JVM_GetClassInterfaces");
1075   JvmtiVMObjectAllocEventCollector oam;
1076   oop mirror = JNIHandles::resolve_non_null(cls);
1077 
1078   // Special handling for primitive objects
1079   if (java_lang_Class::is_primitive(mirror)) {
1080     // Primitive objects does not have any interfaces
1081     objArrayOop r = oopFactory::new_objArray(SystemDictionary::Class_klass(), 0, CHECK_NULL);
1082     return (jobjectArray) JNIHandles::make_local(env, r);
1083   }
1084 
1085   Klass* klass = java_lang_Class::as_Klass(mirror);
1086   // Figure size of result array
1087   int size;
1088   if (klass->is_instance_klass()) {
1089     size = InstanceKlass::cast(klass)->local_interfaces()->length();
1090   } else {
1091     assert(klass->is_objArray_klass() || klass->is_typeArray_klass(), "Illegal mirror klass");
1092     size = 2;
1093   }
1094 
1095   // Allocate result array
1096   objArrayOop r = oopFactory::new_objArray(SystemDictionary::Class_klass(), size, CHECK_NULL);
1097   objArrayHandle result (THREAD, r);
1098   // Fill in result
1099   if (klass->is_instance_klass()) {
1100     // Regular instance klass, fill in all local interfaces
1101     for (int index = 0; index < size; index++) {
1102       Klass* k = InstanceKlass::cast(klass)->local_interfaces()->at(index);
1103       result->obj_at_put(index, k->java_mirror());
1104     }
1105   } else {
1106     // All arrays implement java.lang.Cloneable and java.io.Serializable
1107     result->obj_at_put(0, SystemDictionary::Cloneable_klass()->java_mirror());
1108     result->obj_at_put(1, SystemDictionary::Serializable_klass()->java_mirror());
1109   }
1110   return (jobjectArray) JNIHandles::make_local(env, result());
1111 JVM_END
1112 
1113 
1114 JVM_QUICK_ENTRY(jboolean, JVM_IsInterface(JNIEnv *env, jclass cls))
1115   JVMWrapper("JVM_IsInterface");
1116   oop mirror = JNIHandles::resolve_non_null(cls);
1117   if (java_lang_Class::is_primitive(mirror)) {
1118     return JNI_FALSE;
1119   }
1120   Klass* k = java_lang_Class::as_Klass(mirror);
1121   jboolean result = k->is_interface();
1122   assert(!result || k->is_instance_klass(),
1123          "all interfaces are instance types");
1124   // The compiler intrinsic for isInterface tests the
1125   // Klass::_access_flags bits in the same way.
1126   return result;
1127 JVM_END
1128 
1129 
1130 JVM_ENTRY(jobjectArray, JVM_GetClassSigners(JNIEnv *env, jclass cls))
1131   JVMWrapper("JVM_GetClassSigners");
1132   JvmtiVMObjectAllocEventCollector oam;
1133   if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(cls))) {
1134     // There are no signers for primitive types
1135     return NULL;
1136   }
1137 
1138   objArrayHandle signers(THREAD, java_lang_Class::signers(JNIHandles::resolve_non_null(cls)));
1139 
1140   // If there are no signers set in the class, or if the class
1141   // is an array, return NULL.
1142   if (signers == NULL) return NULL;
1143 
1144   // copy of the signers array
1145   Klass* element = ObjArrayKlass::cast(signers->klass())->element_klass();
1146   objArrayOop signers_copy = oopFactory::new_objArray(element, signers->length(), CHECK_NULL);
1147   for (int index = 0; index < signers->length(); index++) {
1148     signers_copy->obj_at_put(index, signers->obj_at(index));
1149   }
1150 
1151   // return the copy
1152   return (jobjectArray) JNIHandles::make_local(env, signers_copy);
1153 JVM_END
1154 
1155 
1156 JVM_ENTRY(void, JVM_SetClassSigners(JNIEnv *env, jclass cls, jobjectArray signers))
1157   JVMWrapper("JVM_SetClassSigners");
1158   if (!java_lang_Class::is_primitive(JNIHandles::resolve_non_null(cls))) {
1159     // This call is ignored for primitive types and arrays.
1160     // Signers are only set once, ClassLoader.java, and thus shouldn't
1161     // be called with an array.  Only the bootstrap loader creates arrays.
1162     Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
1163     if (k->is_instance_klass()) {
1164       java_lang_Class::set_signers(k->java_mirror(), objArrayOop(JNIHandles::resolve(signers)));
1165     }
1166   }
1167 JVM_END
1168 
1169 
1170 JVM_ENTRY(jobject, JVM_GetProtectionDomain(JNIEnv *env, jclass cls))
1171   JVMWrapper("JVM_GetProtectionDomain");
1172   if (JNIHandles::resolve(cls) == NULL) {
1173     THROW_(vmSymbols::java_lang_NullPointerException(), NULL);
1174   }
1175 
1176   if (java_lang_Class::is_primitive(JNIHandles::resolve(cls))) {
1177     // Primitive types does not have a protection domain.
1178     return NULL;
1179   }
1180 
1181   oop pd = java_lang_Class::protection_domain(JNIHandles::resolve(cls));
1182   return (jobject) JNIHandles::make_local(env, pd);
1183 JVM_END
1184 
1185 
1186 // Returns the inherited_access_control_context field of the running thread.
1187 JVM_ENTRY(jobject, JVM_GetInheritedAccessControlContext(JNIEnv *env, jclass cls))
1188   JVMWrapper("JVM_GetInheritedAccessControlContext");
1189   oop result = java_lang_Thread::inherited_access_control_context(thread->threadObj());
1190   return JNIHandles::make_local(env, result);
1191 JVM_END
1192 
1193 class RegisterArrayForGC {
1194  private:
1195   JavaThread *_thread;
1196  public:
1197   RegisterArrayForGC(JavaThread *thread, GrowableArray<oop>* array)  {
1198     _thread = thread;
1199     _thread->register_array_for_gc(array);
1200   }
1201 
1202   ~RegisterArrayForGC() {
1203     _thread->register_array_for_gc(NULL);
1204   }
1205 };
1206 
1207 
1208 JVM_ENTRY(jobject, JVM_GetStackAccessControlContext(JNIEnv *env, jclass cls))
1209   JVMWrapper("JVM_GetStackAccessControlContext");
1210   if (!UsePrivilegedStack) return NULL;
1211 
1212   ResourceMark rm(THREAD);
1213   GrowableArray<oop>* local_array = new GrowableArray<oop>(12);
1214   JvmtiVMObjectAllocEventCollector oam;
1215 
1216   // count the protection domains on the execution stack. We collapse
1217   // duplicate consecutive protection domains into a single one, as
1218   // well as stopping when we hit a privileged frame.
1219 
1220   oop previous_protection_domain = NULL;
1221   Handle privileged_context(thread, NULL);
1222   bool is_privileged = false;
1223   oop protection_domain = NULL;
1224 
1225   // Iterate through Java frames
1226   vframeStream vfst(thread);
1227   for(; !vfst.at_end(); vfst.next()) {
1228     // get method of frame
1229     Method* method = vfst.method();
1230 
1231     // stop at the first privileged frame
1232     if (method->method_holder() == SystemDictionary::AccessController_klass() &&
1233       method->name() == vmSymbols::executePrivileged_name())
1234     {
1235       // this frame is privileged
1236       is_privileged = true;
1237 
1238       javaVFrame *priv = vfst.asJavaVFrame();       // executePrivileged
1239 
1240       StackValueCollection* locals = priv->locals();
1241       StackValue* ctx_sv = locals->at(1); // AccessControlContext context
1242       StackValue* clr_sv = locals->at(2); // Class<?> caller
1243       assert(!ctx_sv->obj_is_scalar_replaced(), "found scalar-replaced object");
1244       assert(!clr_sv->obj_is_scalar_replaced(), "found scalar-replaced object");
1245       privileged_context    = ctx_sv->get_obj();
1246       Handle caller         = clr_sv->get_obj();
1247 
1248       Klass *caller_klass = java_lang_Class::as_Klass(caller());
1249       protection_domain  = caller_klass->protection_domain();
1250     } else {
1251       protection_domain = method->method_holder()->protection_domain();
1252     }
1253 
1254     if ((!oopDesc::equals(previous_protection_domain, protection_domain)) && (protection_domain != NULL)) {
1255       local_array->push(protection_domain);
1256       previous_protection_domain = protection_domain;
1257     }
1258 
1259     if (is_privileged) break;
1260   }
1261 
1262 
1263   // either all the domains on the stack were system domains, or
1264   // we had a privileged system domain
1265   if (local_array->is_empty()) {
1266     if (is_privileged && privileged_context.is_null()) return NULL;
1267 
1268     oop result = java_security_AccessControlContext::create(objArrayHandle(), is_privileged, privileged_context, CHECK_NULL);
1269     return JNIHandles::make_local(env, result);
1270   }
1271 
1272   // the resource area must be registered in case of a gc
1273   RegisterArrayForGC ragc(thread, local_array);
1274   objArrayOop context = oopFactory::new_objArray(SystemDictionary::ProtectionDomain_klass(),
1275                                                  local_array->length(), CHECK_NULL);
1276   objArrayHandle h_context(thread, context);
1277   for (int index = 0; index < local_array->length(); index++) {
1278     h_context->obj_at_put(index, local_array->at(index));
1279   }
1280 
1281   oop result = java_security_AccessControlContext::create(h_context, is_privileged, privileged_context, CHECK_NULL);
1282 
1283   return JNIHandles::make_local(env, result);
1284 JVM_END
1285 
1286 
1287 JVM_QUICK_ENTRY(jboolean, JVM_IsArrayClass(JNIEnv *env, jclass cls))
1288   JVMWrapper("JVM_IsArrayClass");
1289   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
1290   return (k != NULL) && k->is_array_klass() ? true : false;
1291 JVM_END
1292 
1293 
1294 JVM_QUICK_ENTRY(jboolean, JVM_IsPrimitiveClass(JNIEnv *env, jclass cls))
1295   JVMWrapper("JVM_IsPrimitiveClass");
1296   oop mirror = JNIHandles::resolve_non_null(cls);
1297   return (jboolean) java_lang_Class::is_primitive(mirror);
1298 JVM_END
1299 
1300 
1301 JVM_ENTRY(jint, JVM_GetClassModifiers(JNIEnv *env, jclass cls))
1302   JVMWrapper("JVM_GetClassModifiers");
1303   if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(cls))) {
1304     // Primitive type
1305     return JVM_ACC_ABSTRACT | JVM_ACC_FINAL | JVM_ACC_PUBLIC;
1306   }
1307 
1308   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
1309   debug_only(int computed_modifiers = k->compute_modifier_flags(CHECK_0));
1310   assert(k->modifier_flags() == computed_modifiers, "modifiers cache is OK");
1311   return k->modifier_flags();
1312 JVM_END
1313 
1314 
1315 // Inner class reflection ///////////////////////////////////////////////////////////////////////////////
1316 
1317 JVM_ENTRY(jobjectArray, JVM_GetDeclaredClasses(JNIEnv *env, jclass ofClass))
1318   JvmtiVMObjectAllocEventCollector oam;
1319   // ofClass is a reference to a java_lang_Class object. The mirror object
1320   // of an InstanceKlass
1321 
1322   if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(ofClass)) ||
1323       ! java_lang_Class::as_Klass(JNIHandles::resolve_non_null(ofClass))->is_instance_klass()) {
1324     oop result = oopFactory::new_objArray(SystemDictionary::Class_klass(), 0, CHECK_NULL);
1325     return (jobjectArray)JNIHandles::make_local(env, result);
1326   }
1327 
1328   InstanceKlass* k = InstanceKlass::cast(java_lang_Class::as_Klass(JNIHandles::resolve_non_null(ofClass)));
1329   InnerClassesIterator iter(k);
1330 
1331   if (iter.length() == 0) {
1332     // Neither an inner nor outer class
1333     oop result = oopFactory::new_objArray(SystemDictionary::Class_klass(), 0, CHECK_NULL);
1334     return (jobjectArray)JNIHandles::make_local(env, result);
1335   }
1336 
1337   // find inner class info
1338   constantPoolHandle cp(thread, k->constants());
1339   int length = iter.length();
1340 
1341   // Allocate temp. result array
1342   objArrayOop r = oopFactory::new_objArray(SystemDictionary::Class_klass(), length/4, CHECK_NULL);
1343   objArrayHandle result (THREAD, r);
1344   int members = 0;
1345 
1346   for (; !iter.done(); iter.next()) {
1347     int ioff = iter.inner_class_info_index();
1348     int ooff = iter.outer_class_info_index();
1349 
1350     if (ioff != 0 && ooff != 0) {
1351       // Check to see if the name matches the class we're looking for
1352       // before attempting to find the class.
1353       if (cp->klass_name_at_matches(k, ooff)) {
1354         Klass* outer_klass = cp->klass_at(ooff, CHECK_NULL);
1355         if (outer_klass == k) {
1356            Klass* ik = cp->klass_at(ioff, CHECK_NULL);
1357            InstanceKlass* inner_klass = InstanceKlass::cast(ik);
1358 
1359            // Throws an exception if outer klass has not declared k as
1360            // an inner klass
1361            Reflection::check_for_inner_class(k, inner_klass, true, CHECK_NULL);
1362 
1363            result->obj_at_put(members, inner_klass->java_mirror());
1364            members++;
1365         }
1366       }
1367     }
1368   }
1369 
1370   if (members != length) {
1371     // Return array of right length
1372     objArrayOop res = oopFactory::new_objArray(SystemDictionary::Class_klass(), members, CHECK_NULL);
1373     for(int i = 0; i < members; i++) {
1374       res->obj_at_put(i, result->obj_at(i));
1375     }
1376     return (jobjectArray)JNIHandles::make_local(env, res);
1377   }
1378 
1379   return (jobjectArray)JNIHandles::make_local(env, result());
1380 JVM_END
1381 
1382 
1383 JVM_ENTRY(jclass, JVM_GetDeclaringClass(JNIEnv *env, jclass ofClass))
1384 {
1385   // ofClass is a reference to a java_lang_Class object.
1386   if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(ofClass)) ||
1387       ! java_lang_Class::as_Klass(JNIHandles::resolve_non_null(ofClass))->is_instance_klass()) {
1388     return NULL;
1389   }
1390 
1391   bool inner_is_member = false;
1392   Klass* outer_klass
1393     = InstanceKlass::cast(java_lang_Class::as_Klass(JNIHandles::resolve_non_null(ofClass))
1394                           )->compute_enclosing_class(&inner_is_member, CHECK_NULL);
1395   if (outer_klass == NULL)  return NULL;  // already a top-level class
1396   if (!inner_is_member)  return NULL;     // an anonymous class (inside a method)
1397   return (jclass) JNIHandles::make_local(env, outer_klass->java_mirror());
1398 }
1399 JVM_END
1400 
1401 JVM_ENTRY(jstring, JVM_GetSimpleBinaryName(JNIEnv *env, jclass cls))
1402 {
1403   oop mirror = JNIHandles::resolve_non_null(cls);
1404   if (java_lang_Class::is_primitive(mirror) ||
1405       !java_lang_Class::as_Klass(mirror)->is_instance_klass()) {
1406     return NULL;
1407   }
1408   InstanceKlass* k = InstanceKlass::cast(java_lang_Class::as_Klass(mirror));
1409   int ooff = 0, noff = 0;
1410   if (k->find_inner_classes_attr(&ooff, &noff, THREAD)) {
1411     if (noff != 0) {
1412       constantPoolHandle i_cp(thread, k->constants());
1413       Symbol* name = i_cp->symbol_at(noff);
1414       Handle str = java_lang_String::create_from_symbol(name, CHECK_NULL);
1415       return (jstring) JNIHandles::make_local(env, str());
1416     }
1417   }
1418   return NULL;
1419 }
1420 JVM_END
1421 
1422 JVM_ENTRY(jstring, JVM_GetClassSignature(JNIEnv *env, jclass cls))
1423   assert (cls != NULL, "illegal class");
1424   JVMWrapper("JVM_GetClassSignature");
1425   JvmtiVMObjectAllocEventCollector oam;
1426   ResourceMark rm(THREAD);
1427   // Return null for arrays and primatives
1428   if (!java_lang_Class::is_primitive(JNIHandles::resolve(cls))) {
1429     Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve(cls));
1430     if (k->is_instance_klass()) {
1431       Symbol* sym = InstanceKlass::cast(k)->generic_signature();
1432       if (sym == NULL) return NULL;
1433       Handle str = java_lang_String::create_from_symbol(sym, CHECK_NULL);
1434       return (jstring) JNIHandles::make_local(env, str());
1435     }
1436   }
1437   return NULL;
1438 JVM_END
1439 
1440 
1441 JVM_ENTRY(jbyteArray, JVM_GetClassAnnotations(JNIEnv *env, jclass cls))
1442   assert (cls != NULL, "illegal class");
1443   JVMWrapper("JVM_GetClassAnnotations");
1444 
1445   // Return null for arrays and primitives
1446   if (!java_lang_Class::is_primitive(JNIHandles::resolve(cls))) {
1447     Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve(cls));
1448     if (k->is_instance_klass()) {
1449       typeArrayOop a = Annotations::make_java_array(InstanceKlass::cast(k)->class_annotations(), CHECK_NULL);
1450       return (jbyteArray) JNIHandles::make_local(env, a);
1451     }
1452   }
1453   return NULL;
1454 JVM_END
1455 
1456 
1457 static bool jvm_get_field_common(jobject field, fieldDescriptor& fd, TRAPS) {
1458   // some of this code was adapted from from jni_FromReflectedField
1459 
1460   oop reflected = JNIHandles::resolve_non_null(field);
1461   oop mirror    = java_lang_reflect_Field::clazz(reflected);
1462   Klass* k    = java_lang_Class::as_Klass(mirror);
1463   int slot      = java_lang_reflect_Field::slot(reflected);
1464   int modifiers = java_lang_reflect_Field::modifiers(reflected);
1465 
1466   InstanceKlass* ik = InstanceKlass::cast(k);
1467   intptr_t offset = ik->field_offset(slot);
1468 
1469   if (modifiers & JVM_ACC_STATIC) {
1470     // for static fields we only look in the current class
1471     if (!ik->find_local_field_from_offset(offset, true, &fd)) {
1472       assert(false, "cannot find static field");
1473       return false;
1474     }
1475   } else {
1476     // for instance fields we start with the current class and work
1477     // our way up through the superclass chain
1478     if (!ik->find_field_from_offset(offset, false, &fd)) {
1479       assert(false, "cannot find instance field");
1480       return false;
1481     }
1482   }
1483   return true;
1484 }
1485 
1486 static Method* jvm_get_method_common(jobject method) {
1487   // some of this code was adapted from from jni_FromReflectedMethod
1488 
1489   oop reflected = JNIHandles::resolve_non_null(method);
1490   oop mirror    = NULL;
1491   int slot      = 0;
1492 
1493   if (reflected->klass() == SystemDictionary::reflect_Constructor_klass()) {
1494     mirror = java_lang_reflect_Constructor::clazz(reflected);
1495     slot   = java_lang_reflect_Constructor::slot(reflected);
1496   } else {
1497     assert(reflected->klass() == SystemDictionary::reflect_Method_klass(),
1498            "wrong type");
1499     mirror = java_lang_reflect_Method::clazz(reflected);
1500     slot   = java_lang_reflect_Method::slot(reflected);
1501   }
1502   Klass* k = java_lang_Class::as_Klass(mirror);
1503 
1504   Method* m = InstanceKlass::cast(k)->method_with_idnum(slot);
1505   assert(m != NULL, "cannot find method");
1506   return m;  // caller has to deal with NULL in product mode
1507 }
1508 
1509 /* Type use annotations support (JDK 1.8) */
1510 
1511 JVM_ENTRY(jbyteArray, JVM_GetClassTypeAnnotations(JNIEnv *env, jclass cls))
1512   assert (cls != NULL, "illegal class");
1513   JVMWrapper("JVM_GetClassTypeAnnotations");
1514   ResourceMark rm(THREAD);
1515   // Return null for arrays and primitives
1516   if (!java_lang_Class::is_primitive(JNIHandles::resolve(cls))) {
1517     Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve(cls));
1518     if (k->is_instance_klass()) {
1519       AnnotationArray* type_annotations = InstanceKlass::cast(k)->class_type_annotations();
1520       if (type_annotations != NULL) {
1521         typeArrayOop a = Annotations::make_java_array(type_annotations, CHECK_NULL);
1522         return (jbyteArray) JNIHandles::make_local(env, a);
1523       }
1524     }
1525   }
1526   return NULL;
1527 JVM_END
1528 
1529 JVM_ENTRY(jbyteArray, JVM_GetMethodTypeAnnotations(JNIEnv *env, jobject method))
1530   assert (method != NULL, "illegal method");
1531   JVMWrapper("JVM_GetMethodTypeAnnotations");
1532 
1533   // method is a handle to a java.lang.reflect.Method object
1534   Method* m = jvm_get_method_common(method);
1535   if (m == NULL) {
1536     return NULL;
1537   }
1538 
1539   AnnotationArray* type_annotations = m->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   return NULL;
1546 JVM_END
1547 
1548 JVM_ENTRY(jbyteArray, JVM_GetFieldTypeAnnotations(JNIEnv *env, jobject field))
1549   assert (field != NULL, "illegal field");
1550   JVMWrapper("JVM_GetFieldTypeAnnotations");
1551 
1552   fieldDescriptor fd;
1553   bool gotFd = jvm_get_field_common(field, fd, CHECK_NULL);
1554   if (!gotFd) {
1555     return NULL;
1556   }
1557 
1558   return (jbyteArray) JNIHandles::make_local(env, Annotations::make_java_array(fd.type_annotations(), THREAD));
1559 JVM_END
1560 
1561 static void bounds_check(const constantPoolHandle& cp, jint index, TRAPS) {
1562   if (!cp->is_within_bounds(index)) {
1563     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "Constant pool index out of bounds");
1564   }
1565 }
1566 
1567 JVM_ENTRY(jobjectArray, JVM_GetMethodParameters(JNIEnv *env, jobject method))
1568 {
1569   JVMWrapper("JVM_GetMethodParameters");
1570   // method is a handle to a java.lang.reflect.Method object
1571   Method* method_ptr = jvm_get_method_common(method);
1572   methodHandle mh (THREAD, method_ptr);
1573   Handle reflected_method (THREAD, JNIHandles::resolve_non_null(method));
1574   const int num_params = mh->method_parameters_length();
1575 
1576   if (num_params < 0) {
1577     // A -1 return value from method_parameters_length means there is no
1578     // parameter data.  Return null to indicate this to the reflection
1579     // API.
1580     assert(num_params == -1, "num_params should be -1 if it is less than zero");
1581     return (jobjectArray)NULL;
1582   } else {
1583     // Otherwise, we return something up to reflection, even if it is
1584     // a zero-length array.  Why?  Because in some cases this can
1585     // trigger a MalformedParametersException.
1586 
1587     // make sure all the symbols are properly formatted
1588     for (int i = 0; i < num_params; i++) {
1589       MethodParametersElement* params = mh->method_parameters_start();
1590       int index = params[i].name_cp_index;
1591       bounds_check(mh->constants(), index, CHECK_NULL);
1592 
1593       if (0 != index && !mh->constants()->tag_at(index).is_utf8()) {
1594         THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
1595                     "Wrong type at constant pool index");
1596       }
1597 
1598     }
1599 
1600     objArrayOop result_oop = oopFactory::new_objArray(SystemDictionary::reflect_Parameter_klass(), num_params, CHECK_NULL);
1601     objArrayHandle result (THREAD, result_oop);
1602 
1603     for (int i = 0; i < num_params; i++) {
1604       MethodParametersElement* params = mh->method_parameters_start();
1605       // For a 0 index, give a NULL symbol
1606       Symbol* sym = 0 != params[i].name_cp_index ?
1607         mh->constants()->symbol_at(params[i].name_cp_index) : NULL;
1608       int flags = params[i].flags;
1609       oop param = Reflection::new_parameter(reflected_method, i, sym,
1610                                             flags, CHECK_NULL);
1611       result->obj_at_put(i, param);
1612     }
1613     return (jobjectArray)JNIHandles::make_local(env, result());
1614   }
1615 }
1616 JVM_END
1617 
1618 // New (JDK 1.4) reflection implementation /////////////////////////////////////
1619 
1620 JVM_ENTRY(jobjectArray, JVM_GetClassDeclaredFields(JNIEnv *env, jclass ofClass, jboolean publicOnly))
1621 {
1622   JVMWrapper("JVM_GetClassDeclaredFields");
1623   JvmtiVMObjectAllocEventCollector oam;
1624 
1625   // Exclude primitive types and array types
1626   if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(ofClass)) ||
1627       java_lang_Class::as_Klass(JNIHandles::resolve_non_null(ofClass))->is_array_klass()) {
1628     // Return empty array
1629     oop res = oopFactory::new_objArray(SystemDictionary::reflect_Field_klass(), 0, CHECK_NULL);
1630     return (jobjectArray) JNIHandles::make_local(env, res);
1631   }
1632 
1633   InstanceKlass* k = InstanceKlass::cast(java_lang_Class::as_Klass(JNIHandles::resolve_non_null(ofClass)));
1634   constantPoolHandle cp(THREAD, k->constants());
1635 
1636   // Ensure class is linked
1637   k->link_class(CHECK_NULL);
1638 
1639   // Allocate result
1640   int num_fields;
1641 
1642   if (publicOnly) {
1643     num_fields = 0;
1644     for (JavaFieldStream fs(k); !fs.done(); fs.next()) {
1645       if (fs.access_flags().is_public()) ++num_fields;
1646     }
1647   } else {
1648     num_fields = k->java_fields_count();
1649   }
1650 
1651   objArrayOop r = oopFactory::new_objArray(SystemDictionary::reflect_Field_klass(), num_fields, CHECK_NULL);
1652   objArrayHandle result (THREAD, r);
1653 
1654   int out_idx = 0;
1655   fieldDescriptor fd;
1656   for (JavaFieldStream fs(k); !fs.done(); fs.next()) {
1657     if (!publicOnly || fs.access_flags().is_public()) {
1658       fd.reinitialize(k, fs.index());
1659       oop field = Reflection::new_field(&fd, CHECK_NULL);
1660       result->obj_at_put(out_idx, field);
1661       ++out_idx;
1662     }
1663   }
1664   assert(out_idx == num_fields, "just checking");
1665   return (jobjectArray) JNIHandles::make_local(env, result());
1666 }
1667 JVM_END
1668 
1669 static bool select_method(const methodHandle& method, bool want_constructor) {
1670   if (want_constructor) {
1671     return (method->is_initializer() && !method->is_static());
1672   } else {
1673     return  (!method->is_initializer() && !method->is_overpass());
1674   }
1675 }
1676 
1677 static jobjectArray get_class_declared_methods_helper(
1678                                   JNIEnv *env,
1679                                   jclass ofClass, jboolean publicOnly,
1680                                   bool want_constructor,
1681                                   Klass* klass, TRAPS) {
1682 
1683   JvmtiVMObjectAllocEventCollector oam;
1684 
1685   // Exclude primitive types and array types
1686   if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(ofClass))
1687       || java_lang_Class::as_Klass(JNIHandles::resolve_non_null(ofClass))->is_array_klass()) {
1688     // Return empty array
1689     oop res = oopFactory::new_objArray(klass, 0, CHECK_NULL);
1690     return (jobjectArray) JNIHandles::make_local(env, res);
1691   }
1692 
1693   InstanceKlass* k = InstanceKlass::cast(java_lang_Class::as_Klass(JNIHandles::resolve_non_null(ofClass)));
1694 
1695   // Ensure class is linked
1696   k->link_class(CHECK_NULL);
1697 
1698   Array<Method*>* methods = k->methods();
1699   int methods_length = methods->length();
1700 
1701   // Save original method_idnum in case of redefinition, which can change
1702   // the idnum of obsolete methods.  The new method will have the same idnum
1703   // but if we refresh the methods array, the counts will be wrong.
1704   ResourceMark rm(THREAD);
1705   GrowableArray<int>* idnums = new GrowableArray<int>(methods_length);
1706   int num_methods = 0;
1707 
1708   for (int i = 0; i < methods_length; i++) {
1709     methodHandle method(THREAD, methods->at(i));
1710     if (select_method(method, want_constructor)) {
1711       if (!publicOnly || method->is_public()) {
1712         idnums->push(method->method_idnum());
1713         ++num_methods;
1714       }
1715     }
1716   }
1717 
1718   // Allocate result
1719   objArrayOop r = oopFactory::new_objArray(klass, num_methods, CHECK_NULL);
1720   objArrayHandle result (THREAD, r);
1721 
1722   // Now just put the methods that we selected above, but go by their idnum
1723   // in case of redefinition.  The methods can be redefined at any safepoint,
1724   // so above when allocating the oop array and below when creating reflect
1725   // objects.
1726   for (int i = 0; i < num_methods; i++) {
1727     methodHandle method(THREAD, k->method_with_idnum(idnums->at(i)));
1728     if (method.is_null()) {
1729       // Method may have been deleted and seems this API can handle null
1730       // Otherwise should probably put a method that throws NSME
1731       result->obj_at_put(i, NULL);
1732     } else {
1733       oop m;
1734       if (want_constructor) {
1735         m = Reflection::new_constructor(method, CHECK_NULL);
1736       } else {
1737         m = Reflection::new_method(method, false, CHECK_NULL);
1738       }
1739       result->obj_at_put(i, m);
1740     }
1741   }
1742 
1743   return (jobjectArray) JNIHandles::make_local(env, result());
1744 }
1745 
1746 JVM_ENTRY(jobjectArray, JVM_GetClassDeclaredMethods(JNIEnv *env, jclass ofClass, jboolean publicOnly))
1747 {
1748   JVMWrapper("JVM_GetClassDeclaredMethods");
1749   return get_class_declared_methods_helper(env, ofClass, publicOnly,
1750                                            /*want_constructor*/ false,
1751                                            SystemDictionary::reflect_Method_klass(), THREAD);
1752 }
1753 JVM_END
1754 
1755 JVM_ENTRY(jobjectArray, JVM_GetClassDeclaredConstructors(JNIEnv *env, jclass ofClass, jboolean publicOnly))
1756 {
1757   JVMWrapper("JVM_GetClassDeclaredConstructors");
1758   return get_class_declared_methods_helper(env, ofClass, publicOnly,
1759                                            /*want_constructor*/ true,
1760                                            SystemDictionary::reflect_Constructor_klass(), THREAD);
1761 }
1762 JVM_END
1763 
1764 JVM_ENTRY(jint, JVM_GetClassAccessFlags(JNIEnv *env, jclass cls))
1765 {
1766   JVMWrapper("JVM_GetClassAccessFlags");
1767   if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(cls))) {
1768     // Primitive type
1769     return JVM_ACC_ABSTRACT | JVM_ACC_FINAL | JVM_ACC_PUBLIC;
1770   }
1771 
1772   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
1773   return k->access_flags().as_int() & JVM_ACC_WRITTEN_FLAGS;
1774 }
1775 JVM_END
1776 
1777 JVM_ENTRY(jboolean, JVM_AreNestMates(JNIEnv *env, jclass current, jclass member))
1778 {
1779   JVMWrapper("JVM_AreNestMates");
1780   Klass* c = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(current));
1781   assert(c->is_instance_klass(), "must be");
1782   InstanceKlass* ck = InstanceKlass::cast(c);
1783   Klass* m = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(member));
1784   assert(m->is_instance_klass(), "must be");
1785   InstanceKlass* mk = InstanceKlass::cast(m);
1786   return ck->has_nestmate_access_to(mk, THREAD);
1787 }
1788 JVM_END
1789 
1790 JVM_ENTRY(jclass, JVM_GetNestHost(JNIEnv* env, jclass current))
1791 {
1792   // current is not a primitive or array class
1793   JVMWrapper("JVM_GetNestHost");
1794   Klass* c = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(current));
1795   assert(c->is_instance_klass(), "must be");
1796   InstanceKlass* ck = InstanceKlass::cast(c);
1797   // Don't post exceptions if validation fails
1798   InstanceKlass* host = ck->nest_host(NULL, THREAD);
1799   return (jclass) (host == NULL ? NULL :
1800                    JNIHandles::make_local(THREAD, host->java_mirror()));
1801 }
1802 JVM_END
1803 
1804 JVM_ENTRY(jobjectArray, JVM_GetNestMembers(JNIEnv* env, jclass current))
1805 {
1806   // current is not a primitive or array class
1807   JVMWrapper("JVM_GetNestMembers");
1808   Klass* c = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(current));
1809   assert(c->is_instance_klass(), "must be");
1810   InstanceKlass* ck = InstanceKlass::cast(c);
1811   // Get the nest host for this nest - throw ICCE if validation fails
1812   Symbol* icce = vmSymbols::java_lang_IncompatibleClassChangeError();
1813   InstanceKlass* host = ck->nest_host(icce, CHECK_NULL);
1814 
1815   {
1816     JvmtiVMObjectAllocEventCollector oam;
1817     Array<u2>* members = host->nest_members();
1818     int length = members == NULL ? 0 : members->length();
1819     // nest host is first in the array so make it one bigger
1820     objArrayOop r = oopFactory::new_objArray(SystemDictionary::Class_klass(),
1821                                              length + 1, CHECK_NULL);
1822     objArrayHandle result (THREAD, r);
1823     result->obj_at_put(0, host->java_mirror());
1824     if (length != 0) {
1825       int i;
1826       for (i = 0; i < length; i++) {
1827          int cp_index = members->at(i);
1828          Klass* k = host->constants()->klass_at(cp_index, CHECK_NULL);
1829          if (k->is_instance_klass()) {
1830            InstanceKlass* nest_host_k =
1831              InstanceKlass::cast(k)->nest_host(icce, CHECK_NULL);
1832            if (nest_host_k == host) {
1833              result->obj_at_put(i+1, k->java_mirror());
1834            }
1835            else {
1836              // k's nest host is legal but it isn't our host so
1837              // throw ICCE
1838              ResourceMark rm(THREAD);
1839              Exceptions::fthrow(THREAD_AND_LOCATION,
1840                                 icce,
1841                                 "Nest member %s in %s declares a different nest host of %s",
1842                                 k->external_name(),
1843                                 host->external_name(),
1844                                 nest_host_k->external_name()
1845                            );
1846              return NULL;
1847            }
1848          }
1849          else {
1850            // we have a bad nest member entry - throw ICCE
1851            ResourceMark rm(THREAD);
1852            Exceptions::fthrow(THREAD_AND_LOCATION,
1853                               icce,
1854                               "Class %s can not be a nest member of %s",
1855                               k->external_name(),
1856                               host->external_name()
1857                               );
1858            return NULL;
1859          }
1860       }
1861     }
1862     else {
1863       assert(host == ck, "must be singleton nest");
1864     }
1865     return (jobjectArray)JNIHandles::make_local(THREAD, result());
1866   }
1867 }
1868 JVM_END
1869 
1870 // Constant pool access //////////////////////////////////////////////////////////
1871 
1872 JVM_ENTRY(jobject, JVM_GetClassConstantPool(JNIEnv *env, jclass cls))
1873 {
1874   JVMWrapper("JVM_GetClassConstantPool");
1875   JvmtiVMObjectAllocEventCollector oam;
1876 
1877   // Return null for primitives and arrays
1878   if (!java_lang_Class::is_primitive(JNIHandles::resolve_non_null(cls))) {
1879     Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
1880     if (k->is_instance_klass()) {
1881       InstanceKlass* k_h = InstanceKlass::cast(k);
1882       Handle jcp = reflect_ConstantPool::create(CHECK_NULL);
1883       reflect_ConstantPool::set_cp(jcp(), k_h->constants());
1884       return JNIHandles::make_local(jcp());
1885     }
1886   }
1887   return NULL;
1888 }
1889 JVM_END
1890 
1891 
1892 JVM_ENTRY(jint, JVM_ConstantPoolGetSize(JNIEnv *env, jobject obj, jobject unused))
1893 {
1894   JVMWrapper("JVM_ConstantPoolGetSize");
1895   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
1896   return cp->length();
1897 }
1898 JVM_END
1899 
1900 
1901 JVM_ENTRY(jclass, JVM_ConstantPoolGetClassAt(JNIEnv *env, jobject obj, jobject unused, jint index))
1902 {
1903   JVMWrapper("JVM_ConstantPoolGetClassAt");
1904   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
1905   bounds_check(cp, index, CHECK_NULL);
1906   constantTag tag = cp->tag_at(index);
1907   if (!tag.is_klass() && !tag.is_unresolved_klass()) {
1908     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
1909   }
1910   Klass* k = cp->klass_at(index, CHECK_NULL);
1911   return (jclass) JNIHandles::make_local(k->java_mirror());
1912 }
1913 JVM_END
1914 
1915 JVM_ENTRY(jclass, JVM_ConstantPoolGetClassAtIfLoaded(JNIEnv *env, jobject obj, jobject unused, jint index))
1916 {
1917   JVMWrapper("JVM_ConstantPoolGetClassAtIfLoaded");
1918   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
1919   bounds_check(cp, index, CHECK_NULL);
1920   constantTag tag = cp->tag_at(index);
1921   if (!tag.is_klass() && !tag.is_unresolved_klass()) {
1922     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
1923   }
1924   Klass* k = ConstantPool::klass_at_if_loaded(cp, index);
1925   if (k == NULL) return NULL;
1926   return (jclass) JNIHandles::make_local(k->java_mirror());
1927 }
1928 JVM_END
1929 
1930 static jobject get_method_at_helper(const constantPoolHandle& cp, jint index, bool force_resolution, TRAPS) {
1931   constantTag tag = cp->tag_at(index);
1932   if (!tag.is_method() && !tag.is_interface_method()) {
1933     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
1934   }
1935   int klass_ref  = cp->uncached_klass_ref_index_at(index);
1936   Klass* k_o;
1937   if (force_resolution) {
1938     k_o = cp->klass_at(klass_ref, CHECK_NULL);
1939   } else {
1940     k_o = ConstantPool::klass_at_if_loaded(cp, klass_ref);
1941     if (k_o == NULL) return NULL;
1942   }
1943   InstanceKlass* k = InstanceKlass::cast(k_o);
1944   Symbol* name = cp->uncached_name_ref_at(index);
1945   Symbol* sig  = cp->uncached_signature_ref_at(index);
1946   methodHandle m (THREAD, k->find_method(name, sig));
1947   if (m.is_null()) {
1948     THROW_MSG_0(vmSymbols::java_lang_RuntimeException(), "Unable to look up method in target class");
1949   }
1950   oop method;
1951   if (!m->is_initializer() || m->is_static()) {
1952     method = Reflection::new_method(m, true, CHECK_NULL);
1953   } else {
1954     method = Reflection::new_constructor(m, CHECK_NULL);
1955   }
1956   return JNIHandles::make_local(method);
1957 }
1958 
1959 JVM_ENTRY(jobject, JVM_ConstantPoolGetMethodAt(JNIEnv *env, jobject obj, jobject unused, jint index))
1960 {
1961   JVMWrapper("JVM_ConstantPoolGetMethodAt");
1962   JvmtiVMObjectAllocEventCollector oam;
1963   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
1964   bounds_check(cp, index, CHECK_NULL);
1965   jobject res = get_method_at_helper(cp, index, true, CHECK_NULL);
1966   return res;
1967 }
1968 JVM_END
1969 
1970 JVM_ENTRY(jobject, JVM_ConstantPoolGetMethodAtIfLoaded(JNIEnv *env, jobject obj, jobject unused, jint index))
1971 {
1972   JVMWrapper("JVM_ConstantPoolGetMethodAtIfLoaded");
1973   JvmtiVMObjectAllocEventCollector oam;
1974   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
1975   bounds_check(cp, index, CHECK_NULL);
1976   jobject res = get_method_at_helper(cp, index, false, CHECK_NULL);
1977   return res;
1978 }
1979 JVM_END
1980 
1981 static jobject get_field_at_helper(constantPoolHandle cp, jint index, bool force_resolution, TRAPS) {
1982   constantTag tag = cp->tag_at(index);
1983   if (!tag.is_field()) {
1984     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
1985   }
1986   int klass_ref  = cp->uncached_klass_ref_index_at(index);
1987   Klass* k_o;
1988   if (force_resolution) {
1989     k_o = cp->klass_at(klass_ref, CHECK_NULL);
1990   } else {
1991     k_o = ConstantPool::klass_at_if_loaded(cp, klass_ref);
1992     if (k_o == NULL) return NULL;
1993   }
1994   InstanceKlass* k = InstanceKlass::cast(k_o);
1995   Symbol* name = cp->uncached_name_ref_at(index);
1996   Symbol* sig  = cp->uncached_signature_ref_at(index);
1997   fieldDescriptor fd;
1998   Klass* target_klass = k->find_field(name, sig, &fd);
1999   if (target_klass == NULL) {
2000     THROW_MSG_0(vmSymbols::java_lang_RuntimeException(), "Unable to look up field in target class");
2001   }
2002   oop field = Reflection::new_field(&fd, CHECK_NULL);
2003   return JNIHandles::make_local(field);
2004 }
2005 
2006 JVM_ENTRY(jobject, JVM_ConstantPoolGetFieldAt(JNIEnv *env, jobject obj, jobject unusedl, jint index))
2007 {
2008   JVMWrapper("JVM_ConstantPoolGetFieldAt");
2009   JvmtiVMObjectAllocEventCollector oam;
2010   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2011   bounds_check(cp, index, CHECK_NULL);
2012   jobject res = get_field_at_helper(cp, index, true, CHECK_NULL);
2013   return res;
2014 }
2015 JVM_END
2016 
2017 JVM_ENTRY(jobject, JVM_ConstantPoolGetFieldAtIfLoaded(JNIEnv *env, jobject obj, jobject unused, jint index))
2018 {
2019   JVMWrapper("JVM_ConstantPoolGetFieldAtIfLoaded");
2020   JvmtiVMObjectAllocEventCollector oam;
2021   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2022   bounds_check(cp, index, CHECK_NULL);
2023   jobject res = get_field_at_helper(cp, index, false, CHECK_NULL);
2024   return res;
2025 }
2026 JVM_END
2027 
2028 JVM_ENTRY(jobjectArray, JVM_ConstantPoolGetMemberRefInfoAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2029 {
2030   JVMWrapper("JVM_ConstantPoolGetMemberRefInfoAt");
2031   JvmtiVMObjectAllocEventCollector oam;
2032   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2033   bounds_check(cp, index, CHECK_NULL);
2034   constantTag tag = cp->tag_at(index);
2035   if (!tag.is_field_or_method()) {
2036     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2037   }
2038   int klass_ref = cp->uncached_klass_ref_index_at(index);
2039   Symbol*  klass_name  = cp->klass_name_at(klass_ref);
2040   Symbol*  member_name = cp->uncached_name_ref_at(index);
2041   Symbol*  member_sig  = cp->uncached_signature_ref_at(index);
2042   objArrayOop  dest_o = oopFactory::new_objArray(SystemDictionary::String_klass(), 3, CHECK_NULL);
2043   objArrayHandle dest(THREAD, dest_o);
2044   Handle str = java_lang_String::create_from_symbol(klass_name, CHECK_NULL);
2045   dest->obj_at_put(0, str());
2046   str = java_lang_String::create_from_symbol(member_name, CHECK_NULL);
2047   dest->obj_at_put(1, str());
2048   str = java_lang_String::create_from_symbol(member_sig, CHECK_NULL);
2049   dest->obj_at_put(2, str());
2050   return (jobjectArray) JNIHandles::make_local(dest());
2051 }
2052 JVM_END
2053 
2054 JVM_ENTRY(jint, JVM_ConstantPoolGetClassRefIndexAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2055 {
2056   JVMWrapper("JVM_ConstantPoolGetClassRefIndexAt");
2057   JvmtiVMObjectAllocEventCollector oam;
2058   constantPoolHandle cp(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2059   bounds_check(cp, index, CHECK_0);
2060   constantTag tag = cp->tag_at(index);
2061   if (!tag.is_field_or_method()) {
2062     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2063   }
2064   return (jint) cp->uncached_klass_ref_index_at(index);
2065 }
2066 JVM_END
2067 
2068 JVM_ENTRY(jint, JVM_ConstantPoolGetNameAndTypeRefIndexAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2069 {
2070   JVMWrapper("JVM_ConstantPoolGetNameAndTypeRefIndexAt");
2071   JvmtiVMObjectAllocEventCollector oam;
2072   constantPoolHandle cp(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2073   bounds_check(cp, index, CHECK_0);
2074   constantTag tag = cp->tag_at(index);
2075   if (!tag.is_invoke_dynamic() && !tag.is_field_or_method()) {
2076     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2077   }
2078   return (jint) cp->uncached_name_and_type_ref_index_at(index);
2079 }
2080 JVM_END
2081 
2082 JVM_ENTRY(jobjectArray, JVM_ConstantPoolGetNameAndTypeRefInfoAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2083 {
2084   JVMWrapper("JVM_ConstantPoolGetNameAndTypeRefInfoAt");
2085   JvmtiVMObjectAllocEventCollector oam;
2086   constantPoolHandle cp(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2087   bounds_check(cp, index, CHECK_NULL);
2088   constantTag tag = cp->tag_at(index);
2089   if (!tag.is_name_and_type()) {
2090     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2091   }
2092   Symbol* member_name = cp->symbol_at(cp->name_ref_index_at(index));
2093   Symbol* member_sig = cp->symbol_at(cp->signature_ref_index_at(index));
2094   objArrayOop dest_o = oopFactory::new_objArray(SystemDictionary::String_klass(), 2, CHECK_NULL);
2095   objArrayHandle dest(THREAD, dest_o);
2096   Handle str = java_lang_String::create_from_symbol(member_name, CHECK_NULL);
2097   dest->obj_at_put(0, str());
2098   str = java_lang_String::create_from_symbol(member_sig, CHECK_NULL);
2099   dest->obj_at_put(1, str());
2100   return (jobjectArray) JNIHandles::make_local(dest());
2101 }
2102 JVM_END
2103 
2104 JVM_ENTRY(jint, JVM_ConstantPoolGetIntAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2105 {
2106   JVMWrapper("JVM_ConstantPoolGetIntAt");
2107   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2108   bounds_check(cp, index, CHECK_0);
2109   constantTag tag = cp->tag_at(index);
2110   if (!tag.is_int()) {
2111     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2112   }
2113   return cp->int_at(index);
2114 }
2115 JVM_END
2116 
2117 JVM_ENTRY(jlong, JVM_ConstantPoolGetLongAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2118 {
2119   JVMWrapper("JVM_ConstantPoolGetLongAt");
2120   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2121   bounds_check(cp, index, CHECK_(0L));
2122   constantTag tag = cp->tag_at(index);
2123   if (!tag.is_long()) {
2124     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2125   }
2126   return cp->long_at(index);
2127 }
2128 JVM_END
2129 
2130 JVM_ENTRY(jfloat, JVM_ConstantPoolGetFloatAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2131 {
2132   JVMWrapper("JVM_ConstantPoolGetFloatAt");
2133   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2134   bounds_check(cp, index, CHECK_(0.0f));
2135   constantTag tag = cp->tag_at(index);
2136   if (!tag.is_float()) {
2137     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2138   }
2139   return cp->float_at(index);
2140 }
2141 JVM_END
2142 
2143 JVM_ENTRY(jdouble, JVM_ConstantPoolGetDoubleAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2144 {
2145   JVMWrapper("JVM_ConstantPoolGetDoubleAt");
2146   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2147   bounds_check(cp, index, CHECK_(0.0));
2148   constantTag tag = cp->tag_at(index);
2149   if (!tag.is_double()) {
2150     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2151   }
2152   return cp->double_at(index);
2153 }
2154 JVM_END
2155 
2156 JVM_ENTRY(jstring, JVM_ConstantPoolGetStringAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2157 {
2158   JVMWrapper("JVM_ConstantPoolGetStringAt");
2159   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2160   bounds_check(cp, index, CHECK_NULL);
2161   constantTag tag = cp->tag_at(index);
2162   if (!tag.is_string()) {
2163     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2164   }
2165   oop str = cp->string_at(index, CHECK_NULL);
2166   return (jstring) JNIHandles::make_local(str);
2167 }
2168 JVM_END
2169 
2170 JVM_ENTRY(jstring, JVM_ConstantPoolGetUTF8At(JNIEnv *env, jobject obj, jobject unused, jint index))
2171 {
2172   JVMWrapper("JVM_ConstantPoolGetUTF8At");
2173   JvmtiVMObjectAllocEventCollector oam;
2174   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2175   bounds_check(cp, index, CHECK_NULL);
2176   constantTag tag = cp->tag_at(index);
2177   if (!tag.is_symbol()) {
2178     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2179   }
2180   Symbol* sym = cp->symbol_at(index);
2181   Handle str = java_lang_String::create_from_symbol(sym, CHECK_NULL);
2182   return (jstring) JNIHandles::make_local(str());
2183 }
2184 JVM_END
2185 
2186 JVM_ENTRY(jbyte, JVM_ConstantPoolGetTagAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2187 {
2188   JVMWrapper("JVM_ConstantPoolGetTagAt");
2189   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2190   bounds_check(cp, index, CHECK_0);
2191   constantTag tag = cp->tag_at(index);
2192   jbyte result = tag.value();
2193   // If returned tag values are not from the JVM spec, e.g. tags from 100 to 105,
2194   // they are changed to the corresponding tags from the JVM spec, so that java code in
2195   // sun.reflect.ConstantPool will return only tags from the JVM spec, not internal ones.
2196   if (tag.is_klass_or_reference()) {
2197       result = JVM_CONSTANT_Class;
2198   } else if (tag.is_string_index()) {
2199       result = JVM_CONSTANT_String;
2200   } else if (tag.is_method_type_in_error()) {
2201       result = JVM_CONSTANT_MethodType;
2202   } else if (tag.is_method_handle_in_error()) {
2203       result = JVM_CONSTANT_MethodHandle;
2204   } else if (tag.is_dynamic_constant_in_error()) {
2205       result = JVM_CONSTANT_Dynamic;
2206   }
2207   return result;
2208 }
2209 JVM_END
2210 
2211 // Assertion support. //////////////////////////////////////////////////////////
2212 
2213 JVM_ENTRY(jboolean, JVM_DesiredAssertionStatus(JNIEnv *env, jclass unused, jclass cls))
2214   JVMWrapper("JVM_DesiredAssertionStatus");
2215   assert(cls != NULL, "bad class");
2216 
2217   oop r = JNIHandles::resolve(cls);
2218   assert(! java_lang_Class::is_primitive(r), "primitive classes not allowed");
2219   if (java_lang_Class::is_primitive(r)) return false;
2220 
2221   Klass* k = java_lang_Class::as_Klass(r);
2222   assert(k->is_instance_klass(), "must be an instance klass");
2223   if (!k->is_instance_klass()) return false;
2224 
2225   ResourceMark rm(THREAD);
2226   const char* name = k->name()->as_C_string();
2227   bool system_class = k->class_loader() == NULL;
2228   return JavaAssertions::enabled(name, system_class);
2229 
2230 JVM_END
2231 
2232 
2233 // Return a new AssertionStatusDirectives object with the fields filled in with
2234 // command-line assertion arguments (i.e., -ea, -da).
2235 JVM_ENTRY(jobject, JVM_AssertionStatusDirectives(JNIEnv *env, jclass unused))
2236   JVMWrapper("JVM_AssertionStatusDirectives");
2237   JvmtiVMObjectAllocEventCollector oam;
2238   oop asd = JavaAssertions::createAssertionStatusDirectives(CHECK_NULL);
2239   return JNIHandles::make_local(env, asd);
2240 JVM_END
2241 
2242 // Verification ////////////////////////////////////////////////////////////////////////////////
2243 
2244 // Reflection for the verifier /////////////////////////////////////////////////////////////////
2245 
2246 // RedefineClasses support: bug 6214132 caused verification to fail.
2247 // All functions from this section should call the jvmtiThreadSate function:
2248 //   Klass* class_to_verify_considering_redefinition(Klass* klass).
2249 // The function returns a Klass* of the _scratch_class if the verifier
2250 // was invoked in the middle of the class redefinition.
2251 // Otherwise it returns its argument value which is the _the_class Klass*.
2252 // Please, refer to the description in the jvmtiThreadSate.hpp.
2253 
2254 JVM_ENTRY(const char*, JVM_GetClassNameUTF(JNIEnv *env, jclass cls))
2255   JVMWrapper("JVM_GetClassNameUTF");
2256   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2257   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2258   return k->name()->as_utf8();
2259 JVM_END
2260 
2261 
2262 JVM_QUICK_ENTRY(void, JVM_GetClassCPTypes(JNIEnv *env, jclass cls, unsigned char *types))
2263   JVMWrapper("JVM_GetClassCPTypes");
2264   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2265   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2266   // types will have length zero if this is not an InstanceKlass
2267   // (length is determined by call to JVM_GetClassCPEntriesCount)
2268   if (k->is_instance_klass()) {
2269     ConstantPool* cp = InstanceKlass::cast(k)->constants();
2270     for (int index = cp->length() - 1; index >= 0; index--) {
2271       constantTag tag = cp->tag_at(index);
2272       types[index] = (tag.is_unresolved_klass()) ? JVM_CONSTANT_Class : tag.value();
2273     }
2274   }
2275 JVM_END
2276 
2277 
2278 JVM_QUICK_ENTRY(jint, JVM_GetClassCPEntriesCount(JNIEnv *env, jclass cls))
2279   JVMWrapper("JVM_GetClassCPEntriesCount");
2280   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2281   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2282   return (!k->is_instance_klass()) ? 0 : InstanceKlass::cast(k)->constants()->length();
2283 JVM_END
2284 
2285 
2286 JVM_QUICK_ENTRY(jint, JVM_GetClassFieldsCount(JNIEnv *env, jclass cls))
2287   JVMWrapper("JVM_GetClassFieldsCount");
2288   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2289   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2290   return (!k->is_instance_klass()) ? 0 : InstanceKlass::cast(k)->java_fields_count();
2291 JVM_END
2292 
2293 
2294 JVM_QUICK_ENTRY(jint, JVM_GetClassMethodsCount(JNIEnv *env, jclass cls))
2295   JVMWrapper("JVM_GetClassMethodsCount");
2296   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2297   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2298   return (!k->is_instance_klass()) ? 0 : InstanceKlass::cast(k)->methods()->length();
2299 JVM_END
2300 
2301 
2302 // The following methods, used for the verifier, are never called with
2303 // array klasses, so a direct cast to InstanceKlass is safe.
2304 // Typically, these methods are called in a loop with bounds determined
2305 // by the results of JVM_GetClass{Fields,Methods}Count, which return
2306 // zero for arrays.
2307 JVM_QUICK_ENTRY(void, JVM_GetMethodIxExceptionIndexes(JNIEnv *env, jclass cls, jint method_index, unsigned short *exceptions))
2308   JVMWrapper("JVM_GetMethodIxExceptionIndexes");
2309   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2310   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2311   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2312   int length = method->checked_exceptions_length();
2313   if (length > 0) {
2314     CheckedExceptionElement* table= method->checked_exceptions_start();
2315     for (int i = 0; i < length; i++) {
2316       exceptions[i] = table[i].class_cp_index;
2317     }
2318   }
2319 JVM_END
2320 
2321 
2322 JVM_QUICK_ENTRY(jint, JVM_GetMethodIxExceptionsCount(JNIEnv *env, jclass cls, jint method_index))
2323   JVMWrapper("JVM_GetMethodIxExceptionsCount");
2324   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2325   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2326   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2327   return method->checked_exceptions_length();
2328 JVM_END
2329 
2330 
2331 JVM_QUICK_ENTRY(void, JVM_GetMethodIxByteCode(JNIEnv *env, jclass cls, jint method_index, unsigned char *code))
2332   JVMWrapper("JVM_GetMethodIxByteCode");
2333   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2334   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2335   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2336   memcpy(code, method->code_base(), method->code_size());
2337 JVM_END
2338 
2339 
2340 JVM_QUICK_ENTRY(jint, JVM_GetMethodIxByteCodeLength(JNIEnv *env, jclass cls, jint method_index))
2341   JVMWrapper("JVM_GetMethodIxByteCodeLength");
2342   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2343   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2344   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2345   return method->code_size();
2346 JVM_END
2347 
2348 
2349 JVM_QUICK_ENTRY(void, JVM_GetMethodIxExceptionTableEntry(JNIEnv *env, jclass cls, jint method_index, jint entry_index, JVM_ExceptionTableEntryType *entry))
2350   JVMWrapper("JVM_GetMethodIxExceptionTableEntry");
2351   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2352   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2353   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2354   ExceptionTable extable(method);
2355   entry->start_pc   = extable.start_pc(entry_index);
2356   entry->end_pc     = extable.end_pc(entry_index);
2357   entry->handler_pc = extable.handler_pc(entry_index);
2358   entry->catchType  = extable.catch_type_index(entry_index);
2359 JVM_END
2360 
2361 
2362 JVM_QUICK_ENTRY(jint, JVM_GetMethodIxExceptionTableLength(JNIEnv *env, jclass cls, int method_index))
2363   JVMWrapper("JVM_GetMethodIxExceptionTableLength");
2364   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2365   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2366   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2367   return method->exception_table_length();
2368 JVM_END
2369 
2370 
2371 JVM_QUICK_ENTRY(jint, JVM_GetMethodIxModifiers(JNIEnv *env, jclass cls, int method_index))
2372   JVMWrapper("JVM_GetMethodIxModifiers");
2373   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2374   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2375   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2376   return method->access_flags().as_int() & JVM_RECOGNIZED_METHOD_MODIFIERS;
2377 JVM_END
2378 
2379 
2380 JVM_QUICK_ENTRY(jint, JVM_GetFieldIxModifiers(JNIEnv *env, jclass cls, int field_index))
2381   JVMWrapper("JVM_GetFieldIxModifiers");
2382   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2383   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2384   return InstanceKlass::cast(k)->field_access_flags(field_index) & JVM_RECOGNIZED_FIELD_MODIFIERS;
2385 JVM_END
2386 
2387 
2388 JVM_QUICK_ENTRY(jint, JVM_GetMethodIxLocalsCount(JNIEnv *env, jclass cls, int method_index))
2389   JVMWrapper("JVM_GetMethodIxLocalsCount");
2390   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2391   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2392   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2393   return method->max_locals();
2394 JVM_END
2395 
2396 
2397 JVM_QUICK_ENTRY(jint, JVM_GetMethodIxArgsSize(JNIEnv *env, jclass cls, int method_index))
2398   JVMWrapper("JVM_GetMethodIxArgsSize");
2399   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2400   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2401   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2402   return method->size_of_parameters();
2403 JVM_END
2404 
2405 
2406 JVM_QUICK_ENTRY(jint, JVM_GetMethodIxMaxStack(JNIEnv *env, jclass cls, int method_index))
2407   JVMWrapper("JVM_GetMethodIxMaxStack");
2408   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2409   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2410   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2411   return method->verifier_max_stack();
2412 JVM_END
2413 
2414 
2415 JVM_QUICK_ENTRY(jboolean, JVM_IsConstructorIx(JNIEnv *env, jclass cls, int method_index))
2416   JVMWrapper("JVM_IsConstructorIx");
2417   ResourceMark rm(THREAD);
2418   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2419   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2420   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2421   return method->name() == vmSymbols::object_initializer_name();
2422 JVM_END
2423 
2424 
2425 JVM_QUICK_ENTRY(jboolean, JVM_IsVMGeneratedMethodIx(JNIEnv *env, jclass cls, int method_index))
2426   JVMWrapper("JVM_IsVMGeneratedMethodIx");
2427   ResourceMark rm(THREAD);
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->is_overpass();
2432 JVM_END
2433 
2434 JVM_ENTRY(const char*, JVM_GetMethodIxNameUTF(JNIEnv *env, jclass cls, jint method_index))
2435   JVMWrapper("JVM_GetMethodIxIxUTF");
2436   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2437   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2438   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2439   return method->name()->as_utf8();
2440 JVM_END
2441 
2442 
2443 JVM_ENTRY(const char*, JVM_GetMethodIxSignatureUTF(JNIEnv *env, jclass cls, jint method_index))
2444   JVMWrapper("JVM_GetMethodIxSignatureUTF");
2445   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2446   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2447   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2448   return method->signature()->as_utf8();
2449 JVM_END
2450 
2451 /**
2452  * All of these JVM_GetCP-xxx methods are used by the old verifier to
2453  * read entries in the constant pool.  Since the old verifier always
2454  * works on a copy of the code, it will not see any rewriting that
2455  * may possibly occur in the middle of verification.  So it is important
2456  * that nothing it calls tries to use the cpCache instead of the raw
2457  * constant pool, so we must use cp->uncached_x methods when appropriate.
2458  */
2459 JVM_ENTRY(const char*, JVM_GetCPFieldNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2460   JVMWrapper("JVM_GetCPFieldNameUTF");
2461   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2462   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2463   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2464   switch (cp->tag_at(cp_index).value()) {
2465     case JVM_CONSTANT_Fieldref:
2466       return cp->uncached_name_ref_at(cp_index)->as_utf8();
2467     default:
2468       fatal("JVM_GetCPFieldNameUTF: illegal constant");
2469   }
2470   ShouldNotReachHere();
2471   return NULL;
2472 JVM_END
2473 
2474 
2475 JVM_ENTRY(const char*, JVM_GetCPMethodNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2476   JVMWrapper("JVM_GetCPMethodNameUTF");
2477   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2478   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2479   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2480   switch (cp->tag_at(cp_index).value()) {
2481     case JVM_CONSTANT_InterfaceMethodref:
2482     case JVM_CONSTANT_Methodref:
2483       return cp->uncached_name_ref_at(cp_index)->as_utf8();
2484     default:
2485       fatal("JVM_GetCPMethodNameUTF: illegal constant");
2486   }
2487   ShouldNotReachHere();
2488   return NULL;
2489 JVM_END
2490 
2491 
2492 JVM_ENTRY(const char*, JVM_GetCPMethodSignatureUTF(JNIEnv *env, jclass cls, jint cp_index))
2493   JVMWrapper("JVM_GetCPMethodSignatureUTF");
2494   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2495   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2496   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2497   switch (cp->tag_at(cp_index).value()) {
2498     case JVM_CONSTANT_InterfaceMethodref:
2499     case JVM_CONSTANT_Methodref:
2500       return cp->uncached_signature_ref_at(cp_index)->as_utf8();
2501     default:
2502       fatal("JVM_GetCPMethodSignatureUTF: illegal constant");
2503   }
2504   ShouldNotReachHere();
2505   return NULL;
2506 JVM_END
2507 
2508 
2509 JVM_ENTRY(const char*, JVM_GetCPFieldSignatureUTF(JNIEnv *env, jclass cls, jint cp_index))
2510   JVMWrapper("JVM_GetCPFieldSignatureUTF");
2511   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2512   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2513   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2514   switch (cp->tag_at(cp_index).value()) {
2515     case JVM_CONSTANT_Fieldref:
2516       return cp->uncached_signature_ref_at(cp_index)->as_utf8();
2517     default:
2518       fatal("JVM_GetCPFieldSignatureUTF: illegal constant");
2519   }
2520   ShouldNotReachHere();
2521   return NULL;
2522 JVM_END
2523 
2524 
2525 JVM_ENTRY(const char*, JVM_GetCPClassNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2526   JVMWrapper("JVM_GetCPClassNameUTF");
2527   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2528   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2529   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2530   Symbol* classname = cp->klass_name_at(cp_index);
2531   return classname->as_utf8();
2532 JVM_END
2533 
2534 
2535 JVM_ENTRY(const char*, JVM_GetCPFieldClassNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2536   JVMWrapper("JVM_GetCPFieldClassNameUTF");
2537   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2538   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2539   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2540   switch (cp->tag_at(cp_index).value()) {
2541     case JVM_CONSTANT_Fieldref: {
2542       int class_index = cp->uncached_klass_ref_index_at(cp_index);
2543       Symbol* classname = cp->klass_name_at(class_index);
2544       return classname->as_utf8();
2545     }
2546     default:
2547       fatal("JVM_GetCPFieldClassNameUTF: illegal constant");
2548   }
2549   ShouldNotReachHere();
2550   return NULL;
2551 JVM_END
2552 
2553 
2554 JVM_ENTRY(const char*, JVM_GetCPMethodClassNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2555   JVMWrapper("JVM_GetCPMethodClassNameUTF");
2556   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2557   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2558   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2559   switch (cp->tag_at(cp_index).value()) {
2560     case JVM_CONSTANT_Methodref:
2561     case JVM_CONSTANT_InterfaceMethodref: {
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_GetCPMethodClassNameUTF: illegal constant");
2568   }
2569   ShouldNotReachHere();
2570   return NULL;
2571 JVM_END
2572 
2573 
2574 JVM_ENTRY(jint, JVM_GetCPFieldModifiers(JNIEnv *env, jclass cls, int cp_index, jclass called_cls))
2575   JVMWrapper("JVM_GetCPFieldModifiers");
2576   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2577   Klass* k_called = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(called_cls));
2578   k        = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2579   k_called = JvmtiThreadState::class_to_verify_considering_redefinition(k_called, thread);
2580   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2581   ConstantPool* cp_called = InstanceKlass::cast(k_called)->constants();
2582   switch (cp->tag_at(cp_index).value()) {
2583     case JVM_CONSTANT_Fieldref: {
2584       Symbol* name      = cp->uncached_name_ref_at(cp_index);
2585       Symbol* signature = cp->uncached_signature_ref_at(cp_index);
2586       InstanceKlass* ik = InstanceKlass::cast(k_called);
2587       for (JavaFieldStream fs(ik); !fs.done(); fs.next()) {
2588         if (fs.name() == name && fs.signature() == signature) {
2589           return fs.access_flags().as_short() & JVM_RECOGNIZED_FIELD_MODIFIERS;
2590         }
2591       }
2592       return -1;
2593     }
2594     default:
2595       fatal("JVM_GetCPFieldModifiers: illegal constant");
2596   }
2597   ShouldNotReachHere();
2598   return 0;
2599 JVM_END
2600 
2601 
2602 JVM_QUICK_ENTRY(jint, JVM_GetCPMethodModifiers(JNIEnv *env, jclass cls, int cp_index, jclass called_cls))
2603   JVMWrapper("JVM_GetCPMethodModifiers");
2604   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2605   Klass* k_called = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(called_cls));
2606   k        = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2607   k_called = JvmtiThreadState::class_to_verify_considering_redefinition(k_called, thread);
2608   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2609   switch (cp->tag_at(cp_index).value()) {
2610     case JVM_CONSTANT_Methodref:
2611     case JVM_CONSTANT_InterfaceMethodref: {
2612       Symbol* name      = cp->uncached_name_ref_at(cp_index);
2613       Symbol* signature = cp->uncached_signature_ref_at(cp_index);
2614       Array<Method*>* methods = InstanceKlass::cast(k_called)->methods();
2615       int methods_count = methods->length();
2616       for (int i = 0; i < methods_count; i++) {
2617         Method* method = methods->at(i);
2618         if (method->name() == name && method->signature() == signature) {
2619             return method->access_flags().as_int() & JVM_RECOGNIZED_METHOD_MODIFIERS;
2620         }
2621       }
2622       return -1;
2623     }
2624     default:
2625       fatal("JVM_GetCPMethodModifiers: illegal constant");
2626   }
2627   ShouldNotReachHere();
2628   return 0;
2629 JVM_END
2630 
2631 
2632 // Misc //////////////////////////////////////////////////////////////////////////////////////////////
2633 
2634 JVM_LEAF(void, JVM_ReleaseUTF(const char *utf))
2635   // So long as UTF8::convert_to_utf8 returns resource strings, we don't have to do anything
2636 JVM_END
2637 
2638 
2639 JVM_ENTRY(jboolean, JVM_IsSameClassPackage(JNIEnv *env, jclass class1, jclass class2))
2640   JVMWrapper("JVM_IsSameClassPackage");
2641   oop class1_mirror = JNIHandles::resolve_non_null(class1);
2642   oop class2_mirror = JNIHandles::resolve_non_null(class2);
2643   Klass* klass1 = java_lang_Class::as_Klass(class1_mirror);
2644   Klass* klass2 = java_lang_Class::as_Klass(class2_mirror);
2645   return (jboolean) Reflection::is_same_class_package(klass1, klass2);
2646 JVM_END
2647 
2648 // Printing support //////////////////////////////////////////////////
2649 extern "C" {
2650 
2651 ATTRIBUTE_PRINTF(3, 0)
2652 int jio_vsnprintf(char *str, size_t count, const char *fmt, va_list args) {
2653   // Reject count values that are negative signed values converted to
2654   // unsigned; see bug 4399518, 4417214
2655   if ((intptr_t)count <= 0) return -1;
2656 
2657   int result = os::vsnprintf(str, count, fmt, args);
2658   if (result > 0 && (size_t)result >= count) {
2659     result = -1;
2660   }
2661 
2662   return result;
2663 }
2664 
2665 ATTRIBUTE_PRINTF(3, 4)
2666 int jio_snprintf(char *str, size_t count, const char *fmt, ...) {
2667   va_list args;
2668   int len;
2669   va_start(args, fmt);
2670   len = jio_vsnprintf(str, count, fmt, args);
2671   va_end(args);
2672   return len;
2673 }
2674 
2675 ATTRIBUTE_PRINTF(2, 3)
2676 int jio_fprintf(FILE* f, const char *fmt, ...) {
2677   int len;
2678   va_list args;
2679   va_start(args, fmt);
2680   len = jio_vfprintf(f, fmt, args);
2681   va_end(args);
2682   return len;
2683 }
2684 
2685 ATTRIBUTE_PRINTF(2, 0)
2686 int jio_vfprintf(FILE* f, const char *fmt, va_list args) {
2687   if (Arguments::vfprintf_hook() != NULL) {
2688      return Arguments::vfprintf_hook()(f, fmt, args);
2689   } else {
2690     return vfprintf(f, fmt, args);
2691   }
2692 }
2693 
2694 ATTRIBUTE_PRINTF(1, 2)
2695 JNIEXPORT int jio_printf(const char *fmt, ...) {
2696   int len;
2697   va_list args;
2698   va_start(args, fmt);
2699   len = jio_vfprintf(defaultStream::output_stream(), fmt, args);
2700   va_end(args);
2701   return len;
2702 }
2703 
2704 // HotSpot specific jio method
2705 void jio_print(const char* s, size_t len) {
2706   // Try to make this function as atomic as possible.
2707   if (Arguments::vfprintf_hook() != NULL) {
2708     jio_fprintf(defaultStream::output_stream(), "%.*s", (int)len, s);
2709   } else {
2710     // Make an unused local variable to avoid warning from gcc 4.x compiler.
2711     size_t count = ::write(defaultStream::output_fd(), s, (int)len);
2712   }
2713 }
2714 
2715 } // Extern C
2716 
2717 // java.lang.Thread //////////////////////////////////////////////////////////////////////////////
2718 
2719 // In most of the JVM thread support functions we need to access the
2720 // thread through a ThreadsListHandle to prevent it from exiting and
2721 // being reclaimed while we try to operate on it. The exceptions to this
2722 // rule are when operating on the current thread, or if the monitor of
2723 // the target java.lang.Thread is locked at the Java level - in both
2724 // cases the target cannot exit.
2725 
2726 static void thread_entry(JavaThread* thread, TRAPS) {
2727   HandleMark hm(THREAD);
2728   Handle obj(THREAD, thread->threadObj());
2729   JavaValue result(T_VOID);
2730   JavaCalls::call_virtual(&result,
2731                           obj,
2732                           SystemDictionary::Thread_klass(),
2733                           vmSymbols::run_method_name(),
2734                           vmSymbols::void_method_signature(),
2735                           THREAD);
2736 }
2737 
2738 
2739 JVM_ENTRY(void, JVM_StartThread(JNIEnv* env, jobject jthread))
2740   JVMWrapper("JVM_StartThread");
2741   JavaThread *native_thread = NULL;
2742 
2743   // We cannot hold the Threads_lock when we throw an exception,
2744   // due to rank ordering issues. Example:  we might need to grab the
2745   // Heap_lock while we construct the exception.
2746   bool throw_illegal_thread_state = false;
2747 
2748   // We must release the Threads_lock before we can post a jvmti event
2749   // in Thread::start.
2750   {
2751     // Ensure that the C++ Thread and OSThread structures aren't freed before
2752     // we operate.
2753     MutexLocker mu(Threads_lock);
2754 
2755     // Since JDK 5 the java.lang.Thread threadStatus is used to prevent
2756     // re-starting an already started thread, so we should usually find
2757     // that the JavaThread is null. However for a JNI attached thread
2758     // there is a small window between the Thread object being created
2759     // (with its JavaThread set) and the update to its threadStatus, so we
2760     // have to check for this
2761     if (java_lang_Thread::thread(JNIHandles::resolve_non_null(jthread)) != NULL) {
2762       throw_illegal_thread_state = true;
2763     } else {
2764       // We could also check the stillborn flag to see if this thread was already stopped, but
2765       // for historical reasons we let the thread detect that itself when it starts running
2766 
2767       jlong size =
2768              java_lang_Thread::stackSize(JNIHandles::resolve_non_null(jthread));
2769       // Allocate the C++ Thread structure and create the native thread.  The
2770       // stack size retrieved from java is 64-bit signed, but the constructor takes
2771       // size_t (an unsigned type), which may be 32 or 64-bit depending on the platform.
2772       //  - Avoid truncating on 32-bit platforms if size is greater than UINT_MAX.
2773       //  - Avoid passing negative values which would result in really large stacks.
2774       NOT_LP64(if (size > SIZE_MAX) size = SIZE_MAX;)
2775       size_t sz = size > 0 ? (size_t) size : 0;
2776       native_thread = new JavaThread(&thread_entry, sz);
2777 
2778       // At this point it may be possible that no osthread was created for the
2779       // JavaThread due to lack of memory. Check for this situation and throw
2780       // an exception if necessary. Eventually we may want to change this so
2781       // that we only grab the lock if the thread was created successfully -
2782       // then we can also do this check and throw the exception in the
2783       // JavaThread constructor.
2784       if (native_thread->osthread() != NULL) {
2785         // Note: the current thread is not being used within "prepare".
2786         native_thread->prepare(jthread);
2787       }
2788     }
2789   }
2790 
2791   if (throw_illegal_thread_state) {
2792     THROW(vmSymbols::java_lang_IllegalThreadStateException());
2793   }
2794 
2795   assert(native_thread != NULL, "Starting null thread?");
2796 
2797   if (native_thread->osthread() == NULL) {
2798     // No one should hold a reference to the 'native_thread'.
2799     native_thread->smr_delete();
2800     if (JvmtiExport::should_post_resource_exhausted()) {
2801       JvmtiExport::post_resource_exhausted(
2802         JVMTI_RESOURCE_EXHAUSTED_OOM_ERROR | JVMTI_RESOURCE_EXHAUSTED_THREADS,
2803         os::native_thread_creation_failed_msg());
2804     }
2805     THROW_MSG(vmSymbols::java_lang_OutOfMemoryError(),
2806               os::native_thread_creation_failed_msg());
2807   }
2808 
2809   Thread::start(native_thread);
2810 
2811 JVM_END
2812 
2813 
2814 // JVM_Stop is implemented using a VM_Operation, so threads are forced to safepoints
2815 // before the quasi-asynchronous exception is delivered.  This is a little obtrusive,
2816 // but is thought to be reliable and simple. In the case, where the receiver is the
2817 // same thread as the sender, no VM_Operation is needed.
2818 JVM_ENTRY(void, JVM_StopThread(JNIEnv* env, jobject jthread, jobject throwable))
2819   JVMWrapper("JVM_StopThread");
2820 
2821   // A nested ThreadsListHandle will grab the Threads_lock so create
2822   // tlh before we resolve throwable.
2823   ThreadsListHandle tlh(thread);
2824   oop java_throwable = JNIHandles::resolve(throwable);
2825   if (java_throwable == NULL) {
2826     THROW(vmSymbols::java_lang_NullPointerException());
2827   }
2828   oop java_thread = NULL;
2829   JavaThread* receiver = NULL;
2830   bool is_alive = tlh.cv_internal_thread_to_JavaThread(jthread, &receiver, &java_thread);
2831   Events::log_exception(thread,
2832                         "JVM_StopThread thread JavaThread " INTPTR_FORMAT " as oop " INTPTR_FORMAT " [exception " INTPTR_FORMAT "]",
2833                         p2i(receiver), p2i((address)java_thread), p2i(throwable));
2834 
2835   if (is_alive) {
2836     // jthread refers to a live JavaThread.
2837     if (thread == receiver) {
2838       // Exception is getting thrown at self so no VM_Operation needed.
2839       THROW_OOP(java_throwable);
2840     } else {
2841       // Use a VM_Operation to throw the exception.
2842       Thread::send_async_exception(java_thread, java_throwable);
2843     }
2844   } else {
2845     // Either:
2846     // - target thread has not been started before being stopped, or
2847     // - target thread already terminated
2848     // We could read the threadStatus to determine which case it is
2849     // but that is overkill as it doesn't matter. We must set the
2850     // stillborn flag for the first case, and if the thread has already
2851     // exited setting this flag has no effect.
2852     java_lang_Thread::set_stillborn(java_thread);
2853   }
2854 JVM_END
2855 
2856 
2857 JVM_ENTRY(jboolean, JVM_IsThreadAlive(JNIEnv* env, jobject jthread))
2858   JVMWrapper("JVM_IsThreadAlive");
2859 
2860   oop thread_oop = JNIHandles::resolve_non_null(jthread);
2861   return java_lang_Thread::is_alive(thread_oop);
2862 JVM_END
2863 
2864 
2865 JVM_ENTRY(void, JVM_SuspendThread(JNIEnv* env, jobject jthread))
2866   JVMWrapper("JVM_SuspendThread");
2867 
2868   ThreadsListHandle tlh(thread);
2869   JavaThread* receiver = NULL;
2870   bool is_alive = tlh.cv_internal_thread_to_JavaThread(jthread, &receiver, NULL);
2871   if (is_alive) {
2872     // jthread refers to a live JavaThread.
2873     {
2874       MutexLocker ml(receiver->SR_lock(), Mutex::_no_safepoint_check_flag);
2875       if (receiver->is_external_suspend()) {
2876         // Don't allow nested external suspend requests. We can't return
2877         // an error from this interface so just ignore the problem.
2878         return;
2879       }
2880       if (receiver->is_exiting()) { // thread is in the process of exiting
2881         return;
2882       }
2883       receiver->set_external_suspend();
2884     }
2885 
2886     // java_suspend() will catch threads in the process of exiting
2887     // and will ignore them.
2888     receiver->java_suspend();
2889 
2890     // It would be nice to have the following assertion in all the
2891     // time, but it is possible for a racing resume request to have
2892     // resumed this thread right after we suspended it. Temporarily
2893     // enable this assertion if you are chasing a different kind of
2894     // bug.
2895     //
2896     // assert(java_lang_Thread::thread(receiver->threadObj()) == NULL ||
2897     //   receiver->is_being_ext_suspended(), "thread is not suspended");
2898   }
2899 JVM_END
2900 
2901 
2902 JVM_ENTRY(void, JVM_ResumeThread(JNIEnv* env, jobject jthread))
2903   JVMWrapper("JVM_ResumeThread");
2904 
2905   ThreadsListHandle tlh(thread);
2906   JavaThread* receiver = NULL;
2907   bool is_alive = tlh.cv_internal_thread_to_JavaThread(jthread, &receiver, NULL);
2908   if (is_alive) {
2909     // jthread refers to a live JavaThread.
2910 
2911     // This is the original comment for this Threads_lock grab:
2912     //   We need to *always* get the threads lock here, since this operation cannot be allowed during
2913     //   a safepoint. The safepoint code relies on suspending a thread to examine its state. If other
2914     //   threads randomly resumes threads, then a thread might not be suspended when the safepoint code
2915     //   looks at it.
2916     //
2917     // The above comment dates back to when we had both internal and
2918     // external suspend APIs that shared a common underlying mechanism.
2919     // External suspend is now entirely cooperative and doesn't share
2920     // anything with internal suspend. That said, there are some
2921     // assumptions in the VM that an external resume grabs the
2922     // Threads_lock. We can't drop the Threads_lock grab here until we
2923     // resolve the assumptions that exist elsewhere.
2924     //
2925     MutexLocker ml(Threads_lock);
2926     receiver->java_resume();
2927   }
2928 JVM_END
2929 
2930 
2931 JVM_ENTRY(void, JVM_SetThreadPriority(JNIEnv* env, jobject jthread, jint prio))
2932   JVMWrapper("JVM_SetThreadPriority");
2933 
2934   ThreadsListHandle tlh(thread);
2935   oop java_thread = NULL;
2936   JavaThread* receiver = NULL;
2937   bool is_alive = tlh.cv_internal_thread_to_JavaThread(jthread, &receiver, &java_thread);
2938   java_lang_Thread::set_priority(java_thread, (ThreadPriority)prio);
2939 
2940   if (is_alive) {
2941     // jthread refers to a live JavaThread.
2942     Thread::set_priority(receiver, (ThreadPriority)prio);
2943   }
2944   // Implied else: If the JavaThread hasn't started yet, then the
2945   // priority set in the java.lang.Thread object above will be pushed
2946   // down when it does start.
2947 JVM_END
2948 
2949 
2950 JVM_ENTRY(void, JVM_Yield(JNIEnv *env, jclass threadClass))
2951   JVMWrapper("JVM_Yield");
2952   if (os::dont_yield()) return;
2953   HOTSPOT_THREAD_YIELD();
2954   os::naked_yield();
2955 JVM_END
2956 
2957 static void post_thread_sleep_event(EventThreadSleep* event, jlong millis) {
2958   assert(event != NULL, "invariant");
2959   assert(event->should_commit(), "invariant");
2960   event->set_time(millis);
2961   event->commit();
2962 }
2963 
2964 JVM_ENTRY(void, JVM_Sleep(JNIEnv* env, jclass threadClass, jlong millis))
2965   JVMWrapper("JVM_Sleep");
2966 
2967   if (millis < 0) {
2968     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "timeout value is negative");
2969   }
2970 
2971   if (Thread::is_interrupted (THREAD, true) && !HAS_PENDING_EXCEPTION) {
2972     THROW_MSG(vmSymbols::java_lang_InterruptedException(), "sleep interrupted");
2973   }
2974 
2975   // Save current thread state and restore it at the end of this block.
2976   // And set new thread state to SLEEPING.
2977   JavaThreadSleepState jtss(thread);
2978 
2979   HOTSPOT_THREAD_SLEEP_BEGIN(millis);
2980   EventThreadSleep event;
2981 
2982   if (millis == 0) {
2983     os::naked_yield();
2984   } else {
2985     ThreadState old_state = thread->osthread()->get_state();
2986     thread->osthread()->set_state(SLEEPING);
2987     if (os::sleep(thread, millis, true) == OS_INTRPT) {
2988       // An asynchronous exception (e.g., ThreadDeathException) could have been thrown on
2989       // us while we were sleeping. We do not overwrite those.
2990       if (!HAS_PENDING_EXCEPTION) {
2991         if (event.should_commit()) {
2992           post_thread_sleep_event(&event, millis);
2993         }
2994         HOTSPOT_THREAD_SLEEP_END(1);
2995 
2996         // TODO-FIXME: THROW_MSG returns which means we will not call set_state()
2997         // to properly restore the thread state.  That's likely wrong.
2998         THROW_MSG(vmSymbols::java_lang_InterruptedException(), "sleep interrupted");
2999       }
3000     }
3001     thread->osthread()->set_state(old_state);
3002   }
3003   if (event.should_commit()) {
3004     post_thread_sleep_event(&event, millis);
3005   }
3006   HOTSPOT_THREAD_SLEEP_END(0);
3007 JVM_END
3008 
3009 JVM_ENTRY(jobject, JVM_CurrentThread(JNIEnv* env, jclass threadClass))
3010   JVMWrapper("JVM_CurrentThread");
3011   oop jthread = thread->threadObj();
3012   assert (thread != NULL, "no current thread!");
3013   return JNIHandles::make_local(env, jthread);
3014 JVM_END
3015 
3016 class CountStackFramesTC : public ThreadClosure {
3017   int _count;
3018   bool _suspended;
3019  public:
3020   CountStackFramesTC() : _count(0), _suspended(false) {}
3021   virtual void do_thread(Thread* thread) {
3022     JavaThread* jt = (JavaThread*)thread;
3023     if (!jt->is_external_suspend()) {
3024       // To keep same behavior we fail this operation,
3025       // even if it would work perfectly.
3026       return;
3027     }
3028     _suspended = true;
3029      // Count all java activation, i.e., number of vframes.
3030     for (vframeStream vfst(jt); !vfst.at_end(); vfst.next()) {
3031       // Native frames are not counted.
3032       if (!vfst.method()->is_native()) _count++;
3033     }
3034   }
3035   int count() { return _count; }
3036   int suspended() { return _suspended; }
3037 };
3038 
3039 JVM_ENTRY(jint, JVM_CountStackFrames(JNIEnv* env, jobject jthread))
3040   JVMWrapper("JVM_CountStackFrames");
3041 
3042   ThreadsListHandle tlh(thread);
3043   JavaThread* receiver = NULL;
3044   bool is_alive = tlh.cv_internal_thread_to_JavaThread(jthread, &receiver, NULL);
3045   if (is_alive) {
3046     // jthread refers to a live JavaThread.
3047     CountStackFramesTC csf;
3048     Handshake::execute(&csf, receiver);
3049     if (!csf.suspended()) {
3050       THROW_MSG_0(vmSymbols::java_lang_IllegalThreadStateException(),
3051                   "this thread is not suspended");
3052     }
3053     return csf.count();
3054   }
3055   // Implied else: if JavaThread is not alive simply return a count of 0.
3056   return 0;
3057 JVM_END
3058 
3059 
3060 JVM_ENTRY(void, JVM_Interrupt(JNIEnv* env, jobject jthread))
3061   JVMWrapper("JVM_Interrupt");
3062 
3063   ThreadsListHandle tlh(thread);
3064   JavaThread* receiver = NULL;
3065   bool is_alive = tlh.cv_internal_thread_to_JavaThread(jthread, &receiver, NULL);
3066   if (is_alive) {
3067     // jthread refers to a live JavaThread.
3068     Thread::interrupt(receiver);
3069   }
3070 JVM_END
3071 
3072 
3073 JVM_QUICK_ENTRY(jboolean, JVM_IsInterrupted(JNIEnv* env, jobject jthread, jboolean clear_interrupted))
3074   JVMWrapper("JVM_IsInterrupted");
3075 
3076   ThreadsListHandle tlh(thread);
3077   JavaThread* receiver = NULL;
3078   bool is_alive = tlh.cv_internal_thread_to_JavaThread(jthread, &receiver, NULL);
3079   if (is_alive) {
3080     // jthread refers to a live JavaThread.
3081     return (jboolean) Thread::is_interrupted(receiver, clear_interrupted != 0);
3082   } else {
3083     return JNI_FALSE;
3084   }
3085 JVM_END
3086 
3087 
3088 // Return true iff the current thread has locked the object passed in
3089 
3090 JVM_ENTRY(jboolean, JVM_HoldsLock(JNIEnv* env, jclass threadClass, jobject obj))
3091   JVMWrapper("JVM_HoldsLock");
3092   assert(THREAD->is_Java_thread(), "sanity check");
3093   if (obj == NULL) {
3094     THROW_(vmSymbols::java_lang_NullPointerException(), JNI_FALSE);
3095   }
3096   Handle h_obj(THREAD, JNIHandles::resolve(obj));
3097   return ObjectSynchronizer::current_thread_holds_lock((JavaThread*)THREAD, h_obj);
3098 JVM_END
3099 
3100 
3101 JVM_ENTRY(void, JVM_DumpAllStacks(JNIEnv* env, jclass))
3102   JVMWrapper("JVM_DumpAllStacks");
3103   VM_PrintThreads op;
3104   VMThread::execute(&op);
3105   if (JvmtiExport::should_post_data_dump()) {
3106     JvmtiExport::post_data_dump();
3107   }
3108 JVM_END
3109 
3110 JVM_ENTRY(void, JVM_SetNativeThreadName(JNIEnv* env, jobject jthread, jstring name))
3111   JVMWrapper("JVM_SetNativeThreadName");
3112 
3113   // We don't use a ThreadsListHandle here because the current thread
3114   // must be alive.
3115   oop java_thread = JNIHandles::resolve_non_null(jthread);
3116   JavaThread* thr = java_lang_Thread::thread(java_thread);
3117   if (thread == thr && !thr->has_attached_via_jni()) {
3118     // Thread naming is only supported for the current thread and
3119     // we don't set the name of an attached thread to avoid stepping
3120     // on other programs.
3121     ResourceMark rm(thread);
3122     const char *thread_name = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(name));
3123     os::set_native_thread_name(thread_name);
3124   }
3125 JVM_END
3126 
3127 // java.lang.SecurityManager ///////////////////////////////////////////////////////////////////////
3128 
3129 JVM_ENTRY(jobjectArray, JVM_GetClassContext(JNIEnv *env))
3130   JVMWrapper("JVM_GetClassContext");
3131   ResourceMark rm(THREAD);
3132   JvmtiVMObjectAllocEventCollector oam;
3133   vframeStream vfst(thread);
3134 
3135   if (SystemDictionary::reflect_CallerSensitive_klass() != NULL) {
3136     // This must only be called from SecurityManager.getClassContext
3137     Method* m = vfst.method();
3138     if (!(m->method_holder() == SystemDictionary::SecurityManager_klass() &&
3139           m->name()          == vmSymbols::getClassContext_name() &&
3140           m->signature()     == vmSymbols::void_class_array_signature())) {
3141       THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), "JVM_GetClassContext must only be called from SecurityManager.getClassContext");
3142     }
3143   }
3144 
3145   // Collect method holders
3146   GrowableArray<Klass*>* klass_array = new GrowableArray<Klass*>();
3147   for (; !vfst.at_end(); vfst.security_next()) {
3148     Method* m = vfst.method();
3149     // Native frames are not returned
3150     if (!m->is_ignored_by_security_stack_walk() && !m->is_native()) {
3151       Klass* holder = m->method_holder();
3152       assert(holder->is_klass(), "just checking");
3153       klass_array->append(holder);
3154     }
3155   }
3156 
3157   // Create result array of type [Ljava/lang/Class;
3158   objArrayOop result = oopFactory::new_objArray(SystemDictionary::Class_klass(), klass_array->length(), CHECK_NULL);
3159   // Fill in mirrors corresponding to method holders
3160   for (int i = 0; i < klass_array->length(); i++) {
3161     result->obj_at_put(i, klass_array->at(i)->java_mirror());
3162   }
3163 
3164   return (jobjectArray) JNIHandles::make_local(env, result);
3165 JVM_END
3166 
3167 
3168 // java.lang.Package ////////////////////////////////////////////////////////////////
3169 
3170 
3171 JVM_ENTRY(jstring, JVM_GetSystemPackage(JNIEnv *env, jstring name))
3172   JVMWrapper("JVM_GetSystemPackage");
3173   ResourceMark rm(THREAD);
3174   JvmtiVMObjectAllocEventCollector oam;
3175   char* str = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(name));
3176   oop result = ClassLoader::get_system_package(str, CHECK_NULL);
3177   return (jstring) JNIHandles::make_local(result);
3178 JVM_END
3179 
3180 
3181 JVM_ENTRY(jobjectArray, JVM_GetSystemPackages(JNIEnv *env))
3182   JVMWrapper("JVM_GetSystemPackages");
3183   JvmtiVMObjectAllocEventCollector oam;
3184   objArrayOop result = ClassLoader::get_system_packages(CHECK_NULL);
3185   return (jobjectArray) JNIHandles::make_local(result);
3186 JVM_END
3187 
3188 
3189 // java.lang.ref.Reference ///////////////////////////////////////////////////////////////
3190 
3191 
3192 JVM_ENTRY(jobject, JVM_GetAndClearReferencePendingList(JNIEnv* env))
3193   JVMWrapper("JVM_GetAndClearReferencePendingList");
3194 
3195   MonitorLocker ml(Heap_lock);
3196   oop ref = Universe::reference_pending_list();
3197   if (ref != NULL) {
3198     Universe::set_reference_pending_list(NULL);
3199   }
3200   return JNIHandles::make_local(env, ref);
3201 JVM_END
3202 
3203 JVM_ENTRY(jboolean, JVM_HasReferencePendingList(JNIEnv* env))
3204   JVMWrapper("JVM_HasReferencePendingList");
3205   MonitorLocker ml(Heap_lock);
3206   return Universe::has_reference_pending_list();
3207 JVM_END
3208 
3209 JVM_ENTRY(void, JVM_WaitForReferencePendingList(JNIEnv* env))
3210   JVMWrapper("JVM_WaitForReferencePendingList");
3211   MonitorLocker ml(Heap_lock);
3212   while (!Universe::has_reference_pending_list()) {
3213     ml.wait();
3214   }
3215 JVM_END
3216 
3217 
3218 // ObjectInputStream ///////////////////////////////////////////////////////////////
3219 
3220 // Return the first user-defined class loader up the execution stack, or null
3221 // if only code from the bootstrap or platform class loader is on the stack.
3222 
3223 JVM_ENTRY(jobject, JVM_LatestUserDefinedLoader(JNIEnv *env))
3224   for (vframeStream vfst(thread); !vfst.at_end(); vfst.next()) {
3225     vfst.skip_reflection_related_frames(); // Only needed for 1.4 reflection
3226     oop loader = vfst.method()->method_holder()->class_loader();
3227     if (loader != NULL && !SystemDictionary::is_platform_class_loader(loader)) {
3228       return JNIHandles::make_local(env, loader);
3229     }
3230   }
3231   return NULL;
3232 JVM_END
3233 
3234 
3235 // Array ///////////////////////////////////////////////////////////////////////////////////////////
3236 
3237 
3238 // resolve array handle and check arguments
3239 static inline arrayOop check_array(JNIEnv *env, jobject arr, bool type_array_only, TRAPS) {
3240   if (arr == NULL) {
3241     THROW_0(vmSymbols::java_lang_NullPointerException());
3242   }
3243   oop a = JNIHandles::resolve_non_null(arr);
3244   if (!a->is_array()) {
3245     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Argument is not an array");
3246   } else if (type_array_only && !a->is_typeArray()) {
3247     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Argument is not an array of primitive type");
3248   }
3249   return arrayOop(a);
3250 }
3251 
3252 
3253 JVM_ENTRY(jint, JVM_GetArrayLength(JNIEnv *env, jobject arr))
3254   JVMWrapper("JVM_GetArrayLength");
3255   arrayOop a = check_array(env, arr, false, CHECK_0);
3256   return a->length();
3257 JVM_END
3258 
3259 
3260 JVM_ENTRY(jobject, JVM_GetArrayElement(JNIEnv *env, jobject arr, jint index))
3261   JVMWrapper("JVM_Array_Get");
3262   JvmtiVMObjectAllocEventCollector oam;
3263   arrayOop a = check_array(env, arr, false, CHECK_NULL);
3264   jvalue value;
3265   BasicType type = Reflection::array_get(&value, a, index, CHECK_NULL);
3266   oop box = Reflection::box(&value, type, CHECK_NULL);
3267   return JNIHandles::make_local(env, box);
3268 JVM_END
3269 
3270 
3271 JVM_ENTRY(jvalue, JVM_GetPrimitiveArrayElement(JNIEnv *env, jobject arr, jint index, jint wCode))
3272   JVMWrapper("JVM_GetPrimitiveArrayElement");
3273   jvalue value;
3274   value.i = 0; // to initialize value before getting used in CHECK
3275   arrayOop a = check_array(env, arr, true, CHECK_(value));
3276   assert(a->is_typeArray(), "just checking");
3277   BasicType type = Reflection::array_get(&value, a, index, CHECK_(value));
3278   BasicType wide_type = (BasicType) wCode;
3279   if (type != wide_type) {
3280     Reflection::widen(&value, type, wide_type, CHECK_(value));
3281   }
3282   return value;
3283 JVM_END
3284 
3285 
3286 JVM_ENTRY(void, JVM_SetArrayElement(JNIEnv *env, jobject arr, jint index, jobject val))
3287   JVMWrapper("JVM_SetArrayElement");
3288   arrayOop a = check_array(env, arr, false, CHECK);
3289   oop box = JNIHandles::resolve(val);
3290   jvalue value;
3291   value.i = 0; // to initialize value before getting used in CHECK
3292   BasicType value_type;
3293   if (a->is_objArray()) {
3294     // Make sure we do no unbox e.g. java/lang/Integer instances when storing into an object array
3295     value_type = Reflection::unbox_for_regular_object(box, &value);
3296   } else {
3297     value_type = Reflection::unbox_for_primitive(box, &value, CHECK);
3298   }
3299   Reflection::array_set(&value, a, index, value_type, CHECK);
3300 JVM_END
3301 
3302 
3303 JVM_ENTRY(void, JVM_SetPrimitiveArrayElement(JNIEnv *env, jobject arr, jint index, jvalue v, unsigned char vCode))
3304   JVMWrapper("JVM_SetPrimitiveArrayElement");
3305   arrayOop a = check_array(env, arr, true, CHECK);
3306   assert(a->is_typeArray(), "just checking");
3307   BasicType value_type = (BasicType) vCode;
3308   Reflection::array_set(&v, a, index, value_type, CHECK);
3309 JVM_END
3310 
3311 
3312 JVM_ENTRY(jobject, JVM_NewArray(JNIEnv *env, jclass eltClass, jint length))
3313   JVMWrapper("JVM_NewArray");
3314   JvmtiVMObjectAllocEventCollector oam;
3315   oop element_mirror = JNIHandles::resolve(eltClass);
3316   oop result = Reflection::reflect_new_array(element_mirror, length, CHECK_NULL);
3317   return JNIHandles::make_local(env, result);
3318 JVM_END
3319 
3320 
3321 JVM_ENTRY(jobject, JVM_NewMultiArray(JNIEnv *env, jclass eltClass, jintArray dim))
3322   JVMWrapper("JVM_NewMultiArray");
3323   JvmtiVMObjectAllocEventCollector oam;
3324   arrayOop dim_array = check_array(env, dim, true, CHECK_NULL);
3325   oop element_mirror = JNIHandles::resolve(eltClass);
3326   assert(dim_array->is_typeArray(), "just checking");
3327   oop result = Reflection::reflect_new_multi_array(element_mirror, typeArrayOop(dim_array), CHECK_NULL);
3328   return JNIHandles::make_local(env, result);
3329 JVM_END
3330 
3331 
3332 // Library support ///////////////////////////////////////////////////////////////////////////
3333 
3334 JVM_ENTRY_NO_ENV(void*, JVM_LoadLibrary(const char* name))
3335   //%note jvm_ct
3336   JVMWrapper("JVM_LoadLibrary");
3337   char ebuf[1024];
3338   void *load_result;
3339   {
3340     ThreadToNativeFromVM ttnfvm(thread);
3341     load_result = os::dll_load(name, ebuf, sizeof ebuf);
3342   }
3343   if (load_result == NULL) {
3344     char msg[1024];
3345     jio_snprintf(msg, sizeof msg, "%s: %s", name, ebuf);
3346     // Since 'ebuf' may contain a string encoded using
3347     // platform encoding scheme, we need to pass
3348     // Exceptions::unsafe_to_utf8 to the new_exception method
3349     // as the last argument. See bug 6367357.
3350     Handle h_exception =
3351       Exceptions::new_exception(thread,
3352                                 vmSymbols::java_lang_UnsatisfiedLinkError(),
3353                                 msg, Exceptions::unsafe_to_utf8);
3354 
3355     THROW_HANDLE_0(h_exception);
3356   }
3357   return load_result;
3358 JVM_END
3359 
3360 
3361 JVM_LEAF(void, JVM_UnloadLibrary(void* handle))
3362   JVMWrapper("JVM_UnloadLibrary");
3363   os::dll_unload(handle);
3364 JVM_END
3365 
3366 
3367 JVM_LEAF(void*, JVM_FindLibraryEntry(void* handle, const char* name))
3368   JVMWrapper("JVM_FindLibraryEntry");
3369   return os::dll_lookup(handle, name);
3370 JVM_END
3371 
3372 
3373 // JNI version ///////////////////////////////////////////////////////////////////////////////
3374 
3375 JVM_LEAF(jboolean, JVM_IsSupportedJNIVersion(jint version))
3376   JVMWrapper("JVM_IsSupportedJNIVersion");
3377   return Threads::is_supported_jni_version_including_1_1(version);
3378 JVM_END
3379 
3380 
3381 // String support ///////////////////////////////////////////////////////////////////////////
3382 
3383 JVM_ENTRY(jstring, JVM_InternString(JNIEnv *env, jstring str))
3384   JVMWrapper("JVM_InternString");
3385   JvmtiVMObjectAllocEventCollector oam;
3386   if (str == NULL) return NULL;
3387   oop string = JNIHandles::resolve_non_null(str);
3388   oop result = StringTable::intern(string, CHECK_NULL);
3389   return (jstring) JNIHandles::make_local(env, result);
3390 JVM_END
3391 
3392 
3393 // Raw monitor support //////////////////////////////////////////////////////////////////////
3394 
3395 // The lock routine below calls lock_without_safepoint_check in order to get a raw lock
3396 // without interfering with the safepoint mechanism. The routines are not JVM_LEAF because
3397 // they might be called by non-java threads. The JVM_LEAF installs a NoHandleMark check
3398 // that only works with java threads.
3399 
3400 
3401 JNIEXPORT void* JNICALL JVM_RawMonitorCreate(void) {
3402   VM_Exit::block_if_vm_exited();
3403   JVMWrapper("JVM_RawMonitorCreate");
3404   return new Mutex(Mutex::native, "JVM_RawMonitorCreate");
3405 }
3406 
3407 
3408 JNIEXPORT void JNICALL  JVM_RawMonitorDestroy(void *mon) {
3409   VM_Exit::block_if_vm_exited();
3410   JVMWrapper("JVM_RawMonitorDestroy");
3411   delete ((Mutex*) mon);
3412 }
3413 
3414 
3415 JNIEXPORT jint JNICALL JVM_RawMonitorEnter(void *mon) {
3416   VM_Exit::block_if_vm_exited();
3417   JVMWrapper("JVM_RawMonitorEnter");
3418   ((Mutex*) mon)->jvm_raw_lock();
3419   return 0;
3420 }
3421 
3422 
3423 JNIEXPORT void JNICALL JVM_RawMonitorExit(void *mon) {
3424   VM_Exit::block_if_vm_exited();
3425   JVMWrapper("JVM_RawMonitorExit");
3426   ((Mutex*) mon)->jvm_raw_unlock();
3427 }
3428 
3429 
3430 // Shared JNI/JVM entry points //////////////////////////////////////////////////////////////
3431 
3432 jclass find_class_from_class_loader(JNIEnv* env, Symbol* name, jboolean init,
3433                                     Handle loader, Handle protection_domain,
3434                                     jboolean throwError, TRAPS) {
3435   // Security Note:
3436   //   The Java level wrapper will perform the necessary security check allowing
3437   //   us to pass the NULL as the initiating class loader.  The VM is responsible for
3438   //   the checkPackageAccess relative to the initiating class loader via the
3439   //   protection_domain. The protection_domain is passed as NULL by the java code
3440   //   if there is no security manager in 3-arg Class.forName().
3441   Klass* klass = SystemDictionary::resolve_or_fail(name, loader, protection_domain, throwError != 0, CHECK_NULL);
3442 
3443   // Check if we should initialize the class
3444   if (init && klass->is_instance_klass()) {
3445     klass->initialize(CHECK_NULL);
3446   }
3447   return (jclass) JNIHandles::make_local(env, klass->java_mirror());
3448 }
3449 
3450 
3451 // Method ///////////////////////////////////////////////////////////////////////////////////////////
3452 
3453 JVM_ENTRY(jobject, JVM_InvokeMethod(JNIEnv *env, jobject method, jobject obj, jobjectArray args0))
3454   JVMWrapper("JVM_InvokeMethod");
3455   Handle method_handle;
3456   if (thread->stack_available((address) &method_handle) >= JVMInvokeMethodSlack) {
3457     method_handle = Handle(THREAD, JNIHandles::resolve(method));
3458     Handle receiver(THREAD, JNIHandles::resolve(obj));
3459     objArrayHandle args(THREAD, objArrayOop(JNIHandles::resolve(args0)));
3460     oop result = Reflection::invoke_method(method_handle(), receiver, args, CHECK_NULL);
3461     jobject res = JNIHandles::make_local(env, result);
3462     if (JvmtiExport::should_post_vm_object_alloc()) {
3463       oop ret_type = java_lang_reflect_Method::return_type(method_handle());
3464       assert(ret_type != NULL, "sanity check: ret_type oop must not be NULL!");
3465       if (java_lang_Class::is_primitive(ret_type)) {
3466         // Only for primitive type vm allocates memory for java object.
3467         // See box() method.
3468         JvmtiExport::post_vm_object_alloc(JavaThread::current(), result);
3469       }
3470     }
3471     return res;
3472   } else {
3473     THROW_0(vmSymbols::java_lang_StackOverflowError());
3474   }
3475 JVM_END
3476 
3477 
3478 JVM_ENTRY(jobject, JVM_NewInstanceFromConstructor(JNIEnv *env, jobject c, jobjectArray args0))
3479   JVMWrapper("JVM_NewInstanceFromConstructor");
3480   oop constructor_mirror = JNIHandles::resolve(c);
3481   objArrayHandle args(THREAD, objArrayOop(JNIHandles::resolve(args0)));
3482   oop result = Reflection::invoke_constructor(constructor_mirror, args, CHECK_NULL);
3483   jobject res = JNIHandles::make_local(env, result);
3484   if (JvmtiExport::should_post_vm_object_alloc()) {
3485     JvmtiExport::post_vm_object_alloc(JavaThread::current(), result);
3486   }
3487   return res;
3488 JVM_END
3489 
3490 // Atomic ///////////////////////////////////////////////////////////////////////////////////////////
3491 
3492 JVM_LEAF(jboolean, JVM_SupportsCX8())
3493   JVMWrapper("JVM_SupportsCX8");
3494   return VM_Version::supports_cx8();
3495 JVM_END
3496 
3497 JVM_ENTRY(void, JVM_InitializeFromArchive(JNIEnv* env, jclass cls))
3498   JVMWrapper("JVM_InitializeFromArchive");
3499   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve(cls));
3500   assert(k->is_klass(), "just checking");
3501   HeapShared::initialize_from_archived_subgraph(k);
3502 JVM_END
3503 
3504 // Returns an array of all live Thread objects (VM internal JavaThreads,
3505 // jvmti agent threads, and JNI attaching threads  are skipped)
3506 // See CR 6404306 regarding JNI attaching threads
3507 JVM_ENTRY(jobjectArray, JVM_GetAllThreads(JNIEnv *env, jclass dummy))
3508   ResourceMark rm(THREAD);
3509   ThreadsListEnumerator tle(THREAD, false, false);
3510   JvmtiVMObjectAllocEventCollector oam;
3511 
3512   int num_threads = tle.num_threads();
3513   objArrayOop r = oopFactory::new_objArray(SystemDictionary::Thread_klass(), num_threads, CHECK_NULL);
3514   objArrayHandle threads_ah(THREAD, r);
3515 
3516   for (int i = 0; i < num_threads; i++) {
3517     Handle h = tle.get_threadObj(i);
3518     threads_ah->obj_at_put(i, h());
3519   }
3520 
3521   return (jobjectArray) JNIHandles::make_local(env, threads_ah());
3522 JVM_END
3523 
3524 
3525 // Support for java.lang.Thread.getStackTrace() and getAllStackTraces() methods
3526 // Return StackTraceElement[][], each element is the stack trace of a thread in
3527 // the corresponding entry in the given threads array
3528 JVM_ENTRY(jobjectArray, JVM_DumpThreads(JNIEnv *env, jclass threadClass, jobjectArray threads))
3529   JVMWrapper("JVM_DumpThreads");
3530   JvmtiVMObjectAllocEventCollector oam;
3531 
3532   // Check if threads is null
3533   if (threads == NULL) {
3534     THROW_(vmSymbols::java_lang_NullPointerException(), 0);
3535   }
3536 
3537   objArrayOop a = objArrayOop(JNIHandles::resolve_non_null(threads));
3538   objArrayHandle ah(THREAD, a);
3539   int num_threads = ah->length();
3540   // check if threads is non-empty array
3541   if (num_threads == 0) {
3542     THROW_(vmSymbols::java_lang_IllegalArgumentException(), 0);
3543   }
3544 
3545   // check if threads is not an array of objects of Thread class
3546   Klass* k = ObjArrayKlass::cast(ah->klass())->element_klass();
3547   if (k != SystemDictionary::Thread_klass()) {
3548     THROW_(vmSymbols::java_lang_IllegalArgumentException(), 0);
3549   }
3550 
3551   ResourceMark rm(THREAD);
3552 
3553   GrowableArray<instanceHandle>* thread_handle_array = new GrowableArray<instanceHandle>(num_threads);
3554   for (int i = 0; i < num_threads; i++) {
3555     oop thread_obj = ah->obj_at(i);
3556     instanceHandle h(THREAD, (instanceOop) thread_obj);
3557     thread_handle_array->append(h);
3558   }
3559 
3560   // The JavaThread references in thread_handle_array are validated
3561   // in VM_ThreadDump::doit().
3562   Handle stacktraces = ThreadService::dump_stack_traces(thread_handle_array, num_threads, CHECK_NULL);
3563   return (jobjectArray)JNIHandles::make_local(env, stacktraces());
3564 
3565 JVM_END
3566 
3567 // JVM monitoring and management support
3568 JVM_ENTRY_NO_ENV(void*, JVM_GetManagement(jint version))
3569   return Management::get_jmm_interface(version);
3570 JVM_END
3571 
3572 // com.sun.tools.attach.VirtualMachine agent properties support
3573 //
3574 // Initialize the agent properties with the properties maintained in the VM
3575 JVM_ENTRY(jobject, JVM_InitAgentProperties(JNIEnv *env, jobject properties))
3576   JVMWrapper("JVM_InitAgentProperties");
3577   ResourceMark rm;
3578 
3579   Handle props(THREAD, JNIHandles::resolve_non_null(properties));
3580 
3581   PUTPROP(props, "sun.java.command", Arguments::java_command());
3582   PUTPROP(props, "sun.jvm.flags", Arguments::jvm_flags());
3583   PUTPROP(props, "sun.jvm.args", Arguments::jvm_args());
3584   return properties;
3585 JVM_END
3586 
3587 JVM_ENTRY(jobjectArray, JVM_GetEnclosingMethodInfo(JNIEnv *env, jclass ofClass))
3588 {
3589   JVMWrapper("JVM_GetEnclosingMethodInfo");
3590   JvmtiVMObjectAllocEventCollector oam;
3591 
3592   if (ofClass == NULL) {
3593     return NULL;
3594   }
3595   Handle mirror(THREAD, JNIHandles::resolve_non_null(ofClass));
3596   // Special handling for primitive objects
3597   if (java_lang_Class::is_primitive(mirror())) {
3598     return NULL;
3599   }
3600   Klass* k = java_lang_Class::as_Klass(mirror());
3601   if (!k->is_instance_klass()) {
3602     return NULL;
3603   }
3604   InstanceKlass* ik = InstanceKlass::cast(k);
3605   int encl_method_class_idx = ik->enclosing_method_class_index();
3606   if (encl_method_class_idx == 0) {
3607     return NULL;
3608   }
3609   objArrayOop dest_o = oopFactory::new_objArray(SystemDictionary::Object_klass(), 3, CHECK_NULL);
3610   objArrayHandle dest(THREAD, dest_o);
3611   Klass* enc_k = ik->constants()->klass_at(encl_method_class_idx, CHECK_NULL);
3612   dest->obj_at_put(0, enc_k->java_mirror());
3613   int encl_method_method_idx = ik->enclosing_method_method_index();
3614   if (encl_method_method_idx != 0) {
3615     Symbol* sym = ik->constants()->symbol_at(
3616                         extract_low_short_from_int(
3617                           ik->constants()->name_and_type_at(encl_method_method_idx)));
3618     Handle str = java_lang_String::create_from_symbol(sym, CHECK_NULL);
3619     dest->obj_at_put(1, str());
3620     sym = ik->constants()->symbol_at(
3621               extract_high_short_from_int(
3622                 ik->constants()->name_and_type_at(encl_method_method_idx)));
3623     str = java_lang_String::create_from_symbol(sym, CHECK_NULL);
3624     dest->obj_at_put(2, str());
3625   }
3626   return (jobjectArray) JNIHandles::make_local(dest());
3627 }
3628 JVM_END
3629 
3630 JVM_ENTRY(void, JVM_GetVersionInfo(JNIEnv* env, jvm_version_info* info, size_t info_size))
3631 {
3632   memset(info, 0, info_size);
3633 
3634   info->jvm_version = VM_Version::jvm_version();
3635   info->patch_version = VM_Version::vm_patch_version();
3636 
3637   // when we add a new capability in the jvm_version_info struct, we should also
3638   // consider to expose this new capability in the sun.rt.jvmCapabilities jvmstat
3639   // counter defined in runtimeService.cpp.
3640   info->is_attach_supported = AttachListener::is_attach_supported();
3641 }
3642 JVM_END
3643 
3644 // Returns an array of java.lang.String objects containing the input arguments to the VM.
3645 JVM_ENTRY(jobjectArray, JVM_GetVmArguments(JNIEnv *env))
3646   ResourceMark rm(THREAD);
3647 
3648   if (Arguments::num_jvm_args() == 0 && Arguments::num_jvm_flags() == 0) {
3649     return NULL;
3650   }
3651 
3652   char** vm_flags = Arguments::jvm_flags_array();
3653   char** vm_args = Arguments::jvm_args_array();
3654   int num_flags = Arguments::num_jvm_flags();
3655   int num_args = Arguments::num_jvm_args();
3656 
3657   InstanceKlass* ik = SystemDictionary::String_klass();
3658   objArrayOop r = oopFactory::new_objArray(ik, num_args + num_flags, CHECK_NULL);
3659   objArrayHandle result_h(THREAD, r);
3660 
3661   int index = 0;
3662   for (int j = 0; j < num_flags; j++, index++) {
3663     Handle h = java_lang_String::create_from_platform_dependent_str(vm_flags[j], CHECK_NULL);
3664     result_h->obj_at_put(index, h());
3665   }
3666   for (int i = 0; i < num_args; i++, index++) {
3667     Handle h = java_lang_String::create_from_platform_dependent_str(vm_args[i], CHECK_NULL);
3668     result_h->obj_at_put(index, h());
3669   }
3670   return (jobjectArray) JNIHandles::make_local(env, result_h());
3671 JVM_END
3672 
3673 JVM_ENTRY_NO_ENV(jint, JVM_FindSignal(const char *name))
3674   return os::get_signal_number(name);
3675 JVM_END