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