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