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   if (want_constructor) {
1670     return (method->is_initializer() && !method->is_static());
1671   } else {
1672     return  (!method->is_initializer() && !method->is_overpass());
1673   }
1674 }
1675 
1676 static jobjectArray get_class_declared_methods_helper(
1677                                   JNIEnv *env,
1678                                   jclass ofClass, jboolean publicOnly,
1679                                   bool want_constructor,
1680                                   Klass* klass, TRAPS) {
1681 
1682   JvmtiVMObjectAllocEventCollector oam;
1683 
1684   // Exclude primitive types and array types
1685   if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(ofClass))
1686       || java_lang_Class::as_Klass(JNIHandles::resolve_non_null(ofClass))->is_array_klass()) {
1687     // Return empty array
1688     oop res = oopFactory::new_objArray(klass, 0, CHECK_NULL);
1689     return (jobjectArray) JNIHandles::make_local(env, res);
1690   }
1691 
1692   InstanceKlass* k = InstanceKlass::cast(java_lang_Class::as_Klass(JNIHandles::resolve_non_null(ofClass)));
1693 
1694   // Ensure class is linked
1695   k->link_class(CHECK_NULL);
1696 
1697   Array<Method*>* methods = k->methods();
1698   int methods_length = methods->length();
1699 
1700   // Save original method_idnum in case of redefinition, which can change
1701   // the idnum of obsolete methods.  The new method will have the same idnum
1702   // but if we refresh the methods array, the counts will be wrong.
1703   ResourceMark rm(THREAD);
1704   GrowableArray<int>* idnums = new GrowableArray<int>(methods_length);
1705   int num_methods = 0;
1706 
1707   for (int i = 0; i < methods_length; i++) {
1708     methodHandle method(THREAD, methods->at(i));
1709     if (select_method(method, want_constructor)) {
1710       if (!publicOnly || method->is_public()) {
1711         idnums->push(method->method_idnum());
1712         ++num_methods;
1713       }
1714     }
1715   }
1716 
1717   // Allocate result
1718   objArrayOop r = oopFactory::new_objArray(klass, num_methods, CHECK_NULL);
1719   objArrayHandle result (THREAD, r);
1720 
1721   // Now just put the methods that we selected above, but go by their idnum
1722   // in case of redefinition.  The methods can be redefined at any safepoint,
1723   // so above when allocating the oop array and below when creating reflect
1724   // objects.
1725   for (int i = 0; i < num_methods; i++) {
1726     methodHandle method(THREAD, k->method_with_idnum(idnums->at(i)));
1727     if (method.is_null()) {
1728       // Method may have been deleted and seems this API can handle null
1729       // Otherwise should probably put a method that throws NSME
1730       result->obj_at_put(i, NULL);
1731     } else {
1732       oop m;
1733       if (want_constructor) {
1734         m = Reflection::new_constructor(method, CHECK_NULL);
1735       } else {
1736         m = Reflection::new_method(method, false, CHECK_NULL);
1737       }
1738       result->obj_at_put(i, m);
1739     }
1740   }
1741 
1742   return (jobjectArray) JNIHandles::make_local(env, result());
1743 }
1744 
1745 JVM_ENTRY(jobjectArray, JVM_GetClassDeclaredMethods(JNIEnv *env, jclass ofClass, jboolean publicOnly))
1746 {
1747   JVMWrapper("JVM_GetClassDeclaredMethods");
1748   return get_class_declared_methods_helper(env, ofClass, publicOnly,
1749                                            /*want_constructor*/ false,
1750                                            SystemDictionary::reflect_Method_klass(), THREAD);
1751 }
1752 JVM_END
1753 
1754 JVM_ENTRY(jobjectArray, JVM_GetClassDeclaredConstructors(JNIEnv *env, jclass ofClass, jboolean publicOnly))
1755 {
1756   JVMWrapper("JVM_GetClassDeclaredConstructors");
1757   return get_class_declared_methods_helper(env, ofClass, publicOnly,
1758                                            /*want_constructor*/ true,
1759                                            SystemDictionary::reflect_Constructor_klass(), THREAD);
1760 }
1761 JVM_END
1762 
1763 JVM_ENTRY(jint, JVM_GetClassAccessFlags(JNIEnv *env, jclass cls))
1764 {
1765   JVMWrapper("JVM_GetClassAccessFlags");
1766   if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(cls))) {
1767     // Primitive type
1768     return JVM_ACC_ABSTRACT | JVM_ACC_FINAL | JVM_ACC_PUBLIC;
1769   }
1770 
1771   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
1772   return k->access_flags().as_int() & JVM_ACC_WRITTEN_FLAGS;
1773 }
1774 JVM_END
1775 
1776 JVM_ENTRY(jboolean, JVM_AreNestMates(JNIEnv *env, jclass current, jclass member))
1777 {
1778   JVMWrapper("JVM_AreNestMates");
1779   Klass* c = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(current));
1780   assert(c->is_instance_klass(), "must be");
1781   InstanceKlass* ck = InstanceKlass::cast(c);
1782   Klass* m = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(member));
1783   assert(m->is_instance_klass(), "must be");
1784   InstanceKlass* mk = InstanceKlass::cast(m);
1785   return ck->has_nestmate_access_to(mk, THREAD);
1786 }
1787 JVM_END
1788 
1789 JVM_ENTRY(jclass, JVM_GetNestHost(JNIEnv* env, jclass current))
1790 {
1791   // current is not a primitive or array class
1792   JVMWrapper("JVM_GetNestHost");
1793   Klass* c = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(current));
1794   assert(c->is_instance_klass(), "must be");
1795   InstanceKlass* ck = InstanceKlass::cast(c);
1796   // Don't post exceptions if validation fails
1797   InstanceKlass* host = ck->nest_host(NULL, THREAD);
1798   return (jclass) (host == NULL ? NULL :
1799                    JNIHandles::make_local(THREAD, host->java_mirror()));
1800 }
1801 JVM_END
1802 
1803 JVM_ENTRY(jobjectArray, JVM_GetNestMembers(JNIEnv* env, jclass current))
1804 {
1805   // current is not a primitive or array class
1806   JVMWrapper("JVM_GetNestMembers");
1807   Klass* c = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(current));
1808   assert(c->is_instance_klass(), "must be");
1809   InstanceKlass* ck = InstanceKlass::cast(c);
1810   // Get the nest host for this nest - throw ICCE if validation fails
1811   Symbol* icce = vmSymbols::java_lang_IncompatibleClassChangeError();
1812   InstanceKlass* host = ck->nest_host(icce, CHECK_NULL);
1813 
1814   {
1815     JvmtiVMObjectAllocEventCollector oam;
1816     Array<u2>* members = host->nest_members();
1817     int length = members == NULL ? 0 : members->length();
1818     // nest host is first in the array so make it one bigger
1819     objArrayOop r = oopFactory::new_objArray(SystemDictionary::Class_klass(),
1820                                              length + 1, CHECK_NULL);
1821     objArrayHandle result (THREAD, r);
1822     result->obj_at_put(0, host->java_mirror());
1823     if (length != 0) {
1824       int i;
1825       for (i = 0; i < length; i++) {
1826          int cp_index = members->at(i);
1827          Klass* k = host->constants()->klass_at(cp_index, CHECK_NULL);
1828          if (k->is_instance_klass()) {
1829            InstanceKlass* nest_host_k =
1830              InstanceKlass::cast(k)->nest_host(icce, CHECK_NULL);
1831            if (nest_host_k == host) {
1832              result->obj_at_put(i+1, k->java_mirror());
1833            }
1834            else {
1835              // k's nest host is legal but it isn't our host so
1836              // throw ICCE
1837              ResourceMark rm(THREAD);
1838              Exceptions::fthrow(THREAD_AND_LOCATION,
1839                                 icce,
1840                                 "Nest member %s in %s declares a different nest host of %s",
1841                                 k->external_name(),
1842                                 host->external_name(),
1843                                 nest_host_k->external_name()
1844                            );
1845              return NULL;
1846            }
1847          }
1848          else {
1849            // we have a bad nest member entry - throw ICCE
1850            ResourceMark rm(THREAD);
1851            Exceptions::fthrow(THREAD_AND_LOCATION,
1852                               icce,
1853                               "Class %s can not be a nest member of %s",
1854                               k->external_name(),
1855                               host->external_name()
1856                               );
1857            return NULL;
1858          }
1859       }
1860     }
1861     else {
1862       assert(host == ck, "must be singleton nest");
1863     }
1864     return (jobjectArray)JNIHandles::make_local(THREAD, result());
1865   }
1866 }
1867 JVM_END
1868 
1869 // Constant pool access //////////////////////////////////////////////////////////
1870 
1871 JVM_ENTRY(jobject, JVM_GetClassConstantPool(JNIEnv *env, jclass cls))
1872 {
1873   JVMWrapper("JVM_GetClassConstantPool");
1874   JvmtiVMObjectAllocEventCollector oam;
1875 
1876   // Return null for primitives and arrays
1877   if (!java_lang_Class::is_primitive(JNIHandles::resolve_non_null(cls))) {
1878     Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
1879     if (k->is_instance_klass()) {
1880       InstanceKlass* k_h = InstanceKlass::cast(k);
1881       Handle jcp = reflect_ConstantPool::create(CHECK_NULL);
1882       reflect_ConstantPool::set_cp(jcp(), k_h->constants());
1883       return JNIHandles::make_local(jcp());
1884     }
1885   }
1886   return NULL;
1887 }
1888 JVM_END
1889 
1890 
1891 JVM_ENTRY(jint, JVM_ConstantPoolGetSize(JNIEnv *env, jobject obj, jobject unused))
1892 {
1893   JVMWrapper("JVM_ConstantPoolGetSize");
1894   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
1895   return cp->length();
1896 }
1897 JVM_END
1898 
1899 
1900 JVM_ENTRY(jclass, JVM_ConstantPoolGetClassAt(JNIEnv *env, jobject obj, jobject unused, jint index))
1901 {
1902   JVMWrapper("JVM_ConstantPoolGetClassAt");
1903   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
1904   bounds_check(cp, index, CHECK_NULL);
1905   constantTag tag = cp->tag_at(index);
1906   if (!tag.is_klass() && !tag.is_unresolved_klass()) {
1907     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
1908   }
1909   Klass* k = cp->klass_at(index, CHECK_NULL);
1910   return (jclass) JNIHandles::make_local(k->java_mirror());
1911 }
1912 JVM_END
1913 
1914 JVM_ENTRY(jclass, JVM_ConstantPoolGetClassAtIfLoaded(JNIEnv *env, jobject obj, jobject unused, jint index))
1915 {
1916   JVMWrapper("JVM_ConstantPoolGetClassAtIfLoaded");
1917   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
1918   bounds_check(cp, index, CHECK_NULL);
1919   constantTag tag = cp->tag_at(index);
1920   if (!tag.is_klass() && !tag.is_unresolved_klass()) {
1921     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
1922   }
1923   Klass* k = ConstantPool::klass_at_if_loaded(cp, index);
1924   if (k == NULL) return NULL;
1925   return (jclass) JNIHandles::make_local(k->java_mirror());
1926 }
1927 JVM_END
1928 
1929 static jobject get_method_at_helper(const constantPoolHandle& cp, jint index, bool force_resolution, TRAPS) {
1930   constantTag tag = cp->tag_at(index);
1931   if (!tag.is_method() && !tag.is_interface_method()) {
1932     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
1933   }
1934   int klass_ref  = cp->uncached_klass_ref_index_at(index);
1935   Klass* k_o;
1936   if (force_resolution) {
1937     k_o = cp->klass_at(klass_ref, CHECK_NULL);
1938   } else {
1939     k_o = ConstantPool::klass_at_if_loaded(cp, klass_ref);
1940     if (k_o == NULL) return NULL;
1941   }
1942   InstanceKlass* k = InstanceKlass::cast(k_o);
1943   Symbol* name = cp->uncached_name_ref_at(index);
1944   Symbol* sig  = cp->uncached_signature_ref_at(index);
1945   methodHandle m (THREAD, k->find_method(name, sig));
1946   if (m.is_null()) {
1947     THROW_MSG_0(vmSymbols::java_lang_RuntimeException(), "Unable to look up method in target class");
1948   }
1949   oop method;
1950   if (!m->is_initializer() || m->is_static()) {
1951     method = Reflection::new_method(m, true, CHECK_NULL);
1952   } else {
1953     method = Reflection::new_constructor(m, CHECK_NULL);
1954   }
1955   return JNIHandles::make_local(method);
1956 }
1957 
1958 JVM_ENTRY(jobject, JVM_ConstantPoolGetMethodAt(JNIEnv *env, jobject obj, jobject unused, jint index))
1959 {
1960   JVMWrapper("JVM_ConstantPoolGetMethodAt");
1961   JvmtiVMObjectAllocEventCollector oam;
1962   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
1963   bounds_check(cp, index, CHECK_NULL);
1964   jobject res = get_method_at_helper(cp, index, true, CHECK_NULL);
1965   return res;
1966 }
1967 JVM_END
1968 
1969 JVM_ENTRY(jobject, JVM_ConstantPoolGetMethodAtIfLoaded(JNIEnv *env, jobject obj, jobject unused, jint index))
1970 {
1971   JVMWrapper("JVM_ConstantPoolGetMethodAtIfLoaded");
1972   JvmtiVMObjectAllocEventCollector oam;
1973   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
1974   bounds_check(cp, index, CHECK_NULL);
1975   jobject res = get_method_at_helper(cp, index, false, CHECK_NULL);
1976   return res;
1977 }
1978 JVM_END
1979 
1980 static jobject get_field_at_helper(constantPoolHandle cp, jint index, bool force_resolution, TRAPS) {
1981   constantTag tag = cp->tag_at(index);
1982   if (!tag.is_field()) {
1983     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
1984   }
1985   int klass_ref  = cp->uncached_klass_ref_index_at(index);
1986   Klass* k_o;
1987   if (force_resolution) {
1988     k_o = cp->klass_at(klass_ref, CHECK_NULL);
1989   } else {
1990     k_o = ConstantPool::klass_at_if_loaded(cp, klass_ref);
1991     if (k_o == NULL) return NULL;
1992   }
1993   InstanceKlass* k = InstanceKlass::cast(k_o);
1994   Symbol* name = cp->uncached_name_ref_at(index);
1995   Symbol* sig  = cp->uncached_signature_ref_at(index);
1996   fieldDescriptor fd;
1997   Klass* target_klass = k->find_field(name, sig, &fd);
1998   if (target_klass == NULL) {
1999     THROW_MSG_0(vmSymbols::java_lang_RuntimeException(), "Unable to look up field in target class");
2000   }
2001   oop field = Reflection::new_field(&fd, CHECK_NULL);
2002   return JNIHandles::make_local(field);
2003 }
2004 
2005 JVM_ENTRY(jobject, JVM_ConstantPoolGetFieldAt(JNIEnv *env, jobject obj, jobject unusedl, jint index))
2006 {
2007   JVMWrapper("JVM_ConstantPoolGetFieldAt");
2008   JvmtiVMObjectAllocEventCollector oam;
2009   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2010   bounds_check(cp, index, CHECK_NULL);
2011   jobject res = get_field_at_helper(cp, index, true, CHECK_NULL);
2012   return res;
2013 }
2014 JVM_END
2015 
2016 JVM_ENTRY(jobject, JVM_ConstantPoolGetFieldAtIfLoaded(JNIEnv *env, jobject obj, jobject unused, jint index))
2017 {
2018   JVMWrapper("JVM_ConstantPoolGetFieldAtIfLoaded");
2019   JvmtiVMObjectAllocEventCollector oam;
2020   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2021   bounds_check(cp, index, CHECK_NULL);
2022   jobject res = get_field_at_helper(cp, index, false, CHECK_NULL);
2023   return res;
2024 }
2025 JVM_END
2026 
2027 JVM_ENTRY(jobjectArray, JVM_ConstantPoolGetMemberRefInfoAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2028 {
2029   JVMWrapper("JVM_ConstantPoolGetMemberRefInfoAt");
2030   JvmtiVMObjectAllocEventCollector oam;
2031   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2032   bounds_check(cp, index, CHECK_NULL);
2033   constantTag tag = cp->tag_at(index);
2034   if (!tag.is_field_or_method()) {
2035     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2036   }
2037   int klass_ref = cp->uncached_klass_ref_index_at(index);
2038   Symbol*  klass_name  = cp->klass_name_at(klass_ref);
2039   Symbol*  member_name = cp->uncached_name_ref_at(index);
2040   Symbol*  member_sig  = cp->uncached_signature_ref_at(index);
2041   objArrayOop  dest_o = oopFactory::new_objArray(SystemDictionary::String_klass(), 3, CHECK_NULL);
2042   objArrayHandle dest(THREAD, dest_o);
2043   Handle str = java_lang_String::create_from_symbol(klass_name, CHECK_NULL);
2044   dest->obj_at_put(0, str());
2045   str = java_lang_String::create_from_symbol(member_name, CHECK_NULL);
2046   dest->obj_at_put(1, str());
2047   str = java_lang_String::create_from_symbol(member_sig, CHECK_NULL);
2048   dest->obj_at_put(2, str());
2049   return (jobjectArray) JNIHandles::make_local(dest());
2050 }
2051 JVM_END
2052 
2053 JVM_ENTRY(jint, JVM_ConstantPoolGetClassRefIndexAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2054 {
2055   JVMWrapper("JVM_ConstantPoolGetClassRefIndexAt");
2056   JvmtiVMObjectAllocEventCollector oam;
2057   constantPoolHandle cp(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2058   bounds_check(cp, index, CHECK_0);
2059   constantTag tag = cp->tag_at(index);
2060   if (!tag.is_field_or_method()) {
2061     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2062   }
2063   return (jint) cp->uncached_klass_ref_index_at(index);
2064 }
2065 JVM_END
2066 
2067 JVM_ENTRY(jint, JVM_ConstantPoolGetNameAndTypeRefIndexAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2068 {
2069   JVMWrapper("JVM_ConstantPoolGetNameAndTypeRefIndexAt");
2070   JvmtiVMObjectAllocEventCollector oam;
2071   constantPoolHandle cp(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2072   bounds_check(cp, index, CHECK_0);
2073   constantTag tag = cp->tag_at(index);
2074   if (!tag.is_invoke_dynamic() && !tag.is_field_or_method()) {
2075     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2076   }
2077   return (jint) cp->uncached_name_and_type_ref_index_at(index);
2078 }
2079 JVM_END
2080 
2081 JVM_ENTRY(jobjectArray, JVM_ConstantPoolGetNameAndTypeRefInfoAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2082 {
2083   JVMWrapper("JVM_ConstantPoolGetNameAndTypeRefInfoAt");
2084   JvmtiVMObjectAllocEventCollector oam;
2085   constantPoolHandle cp(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2086   bounds_check(cp, index, CHECK_NULL);
2087   constantTag tag = cp->tag_at(index);
2088   if (!tag.is_name_and_type()) {
2089     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2090   }
2091   Symbol* member_name = cp->symbol_at(cp->name_ref_index_at(index));
2092   Symbol* member_sig = cp->symbol_at(cp->signature_ref_index_at(index));
2093   objArrayOop dest_o = oopFactory::new_objArray(SystemDictionary::String_klass(), 2, CHECK_NULL);
2094   objArrayHandle dest(THREAD, dest_o);
2095   Handle str = java_lang_String::create_from_symbol(member_name, CHECK_NULL);
2096   dest->obj_at_put(0, str());
2097   str = java_lang_String::create_from_symbol(member_sig, CHECK_NULL);
2098   dest->obj_at_put(1, str());
2099   return (jobjectArray) JNIHandles::make_local(dest());
2100 }
2101 JVM_END
2102 
2103 JVM_ENTRY(jint, JVM_ConstantPoolGetIntAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2104 {
2105   JVMWrapper("JVM_ConstantPoolGetIntAt");
2106   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2107   bounds_check(cp, index, CHECK_0);
2108   constantTag tag = cp->tag_at(index);
2109   if (!tag.is_int()) {
2110     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2111   }
2112   return cp->int_at(index);
2113 }
2114 JVM_END
2115 
2116 JVM_ENTRY(jlong, JVM_ConstantPoolGetLongAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2117 {
2118   JVMWrapper("JVM_ConstantPoolGetLongAt");
2119   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2120   bounds_check(cp, index, CHECK_(0L));
2121   constantTag tag = cp->tag_at(index);
2122   if (!tag.is_long()) {
2123     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2124   }
2125   return cp->long_at(index);
2126 }
2127 JVM_END
2128 
2129 JVM_ENTRY(jfloat, JVM_ConstantPoolGetFloatAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2130 {
2131   JVMWrapper("JVM_ConstantPoolGetFloatAt");
2132   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2133   bounds_check(cp, index, CHECK_(0.0f));
2134   constantTag tag = cp->tag_at(index);
2135   if (!tag.is_float()) {
2136     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2137   }
2138   return cp->float_at(index);
2139 }
2140 JVM_END
2141 
2142 JVM_ENTRY(jdouble, JVM_ConstantPoolGetDoubleAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2143 {
2144   JVMWrapper("JVM_ConstantPoolGetDoubleAt");
2145   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2146   bounds_check(cp, index, CHECK_(0.0));
2147   constantTag tag = cp->tag_at(index);
2148   if (!tag.is_double()) {
2149     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2150   }
2151   return cp->double_at(index);
2152 }
2153 JVM_END
2154 
2155 JVM_ENTRY(jstring, JVM_ConstantPoolGetStringAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2156 {
2157   JVMWrapper("JVM_ConstantPoolGetStringAt");
2158   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2159   bounds_check(cp, index, CHECK_NULL);
2160   constantTag tag = cp->tag_at(index);
2161   if (!tag.is_string()) {
2162     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2163   }
2164   oop str = cp->string_at(index, CHECK_NULL);
2165   return (jstring) JNIHandles::make_local(str);
2166 }
2167 JVM_END
2168 
2169 JVM_ENTRY(jstring, JVM_ConstantPoolGetUTF8At(JNIEnv *env, jobject obj, jobject unused, jint index))
2170 {
2171   JVMWrapper("JVM_ConstantPoolGetUTF8At");
2172   JvmtiVMObjectAllocEventCollector oam;
2173   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2174   bounds_check(cp, index, CHECK_NULL);
2175   constantTag tag = cp->tag_at(index);
2176   if (!tag.is_symbol()) {
2177     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2178   }
2179   Symbol* sym = cp->symbol_at(index);
2180   Handle str = java_lang_String::create_from_symbol(sym, CHECK_NULL);
2181   return (jstring) JNIHandles::make_local(str());
2182 }
2183 JVM_END
2184 
2185 JVM_ENTRY(jbyte, JVM_ConstantPoolGetTagAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2186 {
2187   JVMWrapper("JVM_ConstantPoolGetTagAt");
2188   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2189   bounds_check(cp, index, CHECK_0);
2190   constantTag tag = cp->tag_at(index);
2191   jbyte result = tag.value();
2192   // If returned tag values are not from the JVM spec, e.g. tags from 100 to 105,
2193   // they are changed to the corresponding tags from the JVM spec, so that java code in
2194   // sun.reflect.ConstantPool will return only tags from the JVM spec, not internal ones.
2195   if (tag.is_klass_or_reference()) {
2196       result = JVM_CONSTANT_Class;
2197   } else if (tag.is_string_index()) {
2198       result = JVM_CONSTANT_String;
2199   } else if (tag.is_method_type_in_error()) {
2200       result = JVM_CONSTANT_MethodType;
2201   } else if (tag.is_method_handle_in_error()) {
2202       result = JVM_CONSTANT_MethodHandle;
2203   } else if (tag.is_dynamic_constant_in_error()) {
2204       result = JVM_CONSTANT_Dynamic;
2205   }
2206   return result;
2207 }
2208 JVM_END
2209 
2210 // Assertion support. //////////////////////////////////////////////////////////
2211 
2212 JVM_ENTRY(jboolean, JVM_DesiredAssertionStatus(JNIEnv *env, jclass unused, jclass cls))
2213   JVMWrapper("JVM_DesiredAssertionStatus");
2214   assert(cls != NULL, "bad class");
2215 
2216   oop r = JNIHandles::resolve(cls);
2217   assert(! java_lang_Class::is_primitive(r), "primitive classes not allowed");
2218   if (java_lang_Class::is_primitive(r)) return false;
2219 
2220   Klass* k = java_lang_Class::as_Klass(r);
2221   assert(k->is_instance_klass(), "must be an instance klass");
2222   if (!k->is_instance_klass()) return false;
2223 
2224   ResourceMark rm(THREAD);
2225   const char* name = k->name()->as_C_string();
2226   bool system_class = k->class_loader() == NULL;
2227   return JavaAssertions::enabled(name, system_class);
2228 
2229 JVM_END
2230 
2231 
2232 // Return a new AssertionStatusDirectives object with the fields filled in with
2233 // command-line assertion arguments (i.e., -ea, -da).
2234 JVM_ENTRY(jobject, JVM_AssertionStatusDirectives(JNIEnv *env, jclass unused))
2235   JVMWrapper("JVM_AssertionStatusDirectives");
2236   JvmtiVMObjectAllocEventCollector oam;
2237   oop asd = JavaAssertions::createAssertionStatusDirectives(CHECK_NULL);
2238   return JNIHandles::make_local(env, asd);
2239 JVM_END
2240 
2241 // Arrays support /////////////////////////////////////////////////////////////
2242 
2243 JVM_ENTRY(jboolean, JVM_ArrayIsAccessAtomic(JNIEnv *env, jclass unused, jobject array))
2244   JVMWrapper("JVM_ArrayIsAccessAtomic");
2245   oop o = JNIHandles::resolve(array);
2246   Klass* k = o->klass();
2247   if ((o == NULL) || (!k->is_array_klass())) {
2248     THROW_0(vmSymbols::java_lang_IllegalArgumentException());
2249   }
2250   if (k->is_valueArray_klass()) {
2251     return ValueArrayKlass::cast(k)->is_atomic();
2252   }
2253   return true;
2254 JVM_END
2255 
2256 JVM_ENTRY(jobject, JVM_ArrayEnsureAccessAtomic(JNIEnv *env, jclass unused, jobject array))
2257   JVMWrapper("JVM_ArrayEnsureAccessAtomic");
2258   oop o = JNIHandles::resolve(array);
2259   Klass* k = o->klass();
2260   if ((o == NULL) || (!k->is_array_klass())) {
2261     THROW_0(vmSymbols::java_lang_IllegalArgumentException());
2262   }
2263   if (k->is_valueArray_klass()) {
2264     ValueArrayKlass* vk = ValueArrayKlass::cast(k);
2265     if (!vk->is_atomic()) {
2266       /**
2267        * Need to decide how to implement:
2268        *
2269        * 1) Change to objArrayOop layout, therefore oop->klass() differs so
2270        * then "<atomic>[Qfoo;" klass needs to subclass "[Qfoo;" to pass through
2271        * "checkcast" & "instanceof"
2272        *
2273        * 2) Use extra header in the valueArrayOop to flag atomicity required and
2274        * possibly per instance lock structure. Said info, could be placed in
2275        * "trailer" rather than disturb the current arrayOop
2276        */
2277       Unimplemented();
2278     }
2279   }
2280   return array;
2281 JVM_END
2282 
2283 // Verification ////////////////////////////////////////////////////////////////////////////////
2284 
2285 // Reflection for the verifier /////////////////////////////////////////////////////////////////
2286 
2287 // RedefineClasses support: bug 6214132 caused verification to fail.
2288 // All functions from this section should call the jvmtiThreadSate function:
2289 //   Klass* class_to_verify_considering_redefinition(Klass* klass).
2290 // The function returns a Klass* of the _scratch_class if the verifier
2291 // was invoked in the middle of the class redefinition.
2292 // Otherwise it returns its argument value which is the _the_class Klass*.
2293 // Please, refer to the description in the jvmtiThreadSate.hpp.
2294 
2295 JVM_ENTRY(const char*, JVM_GetClassNameUTF(JNIEnv *env, jclass cls))
2296   JVMWrapper("JVM_GetClassNameUTF");
2297   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2298   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2299   return k->name()->as_utf8();
2300 JVM_END
2301 
2302 
2303 JVM_QUICK_ENTRY(void, JVM_GetClassCPTypes(JNIEnv *env, jclass cls, unsigned char *types))
2304   JVMWrapper("JVM_GetClassCPTypes");
2305   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2306   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2307   // types will have length zero if this is not an InstanceKlass
2308   // (length is determined by call to JVM_GetClassCPEntriesCount)
2309   if (k->is_instance_klass()) {
2310     ConstantPool* cp = InstanceKlass::cast(k)->constants();
2311     for (int index = cp->length() - 1; index >= 0; index--) {
2312       constantTag tag = cp->tag_at(index);
2313       types[index] = tag.is_unresolved_klass() ? JVM_CONSTANT_Class : tag.value();
2314     }
2315   }
2316 JVM_END
2317 
2318 
2319 JVM_QUICK_ENTRY(jint, JVM_GetClassCPEntriesCount(JNIEnv *env, jclass cls))
2320   JVMWrapper("JVM_GetClassCPEntriesCount");
2321   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2322   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2323   return (!k->is_instance_klass()) ? 0 : InstanceKlass::cast(k)->constants()->length();
2324 JVM_END
2325 
2326 
2327 JVM_QUICK_ENTRY(jint, JVM_GetClassFieldsCount(JNIEnv *env, jclass cls))
2328   JVMWrapper("JVM_GetClassFieldsCount");
2329   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2330   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2331   return (!k->is_instance_klass()) ? 0 : InstanceKlass::cast(k)->java_fields_count();
2332 JVM_END
2333 
2334 
2335 JVM_QUICK_ENTRY(jint, JVM_GetClassMethodsCount(JNIEnv *env, jclass cls))
2336   JVMWrapper("JVM_GetClassMethodsCount");
2337   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2338   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2339   return (!k->is_instance_klass()) ? 0 : InstanceKlass::cast(k)->methods()->length();
2340 JVM_END
2341 
2342 
2343 // The following methods, used for the verifier, are never called with
2344 // array klasses, so a direct cast to InstanceKlass is safe.
2345 // Typically, these methods are called in a loop with bounds determined
2346 // by the results of JVM_GetClass{Fields,Methods}Count, which return
2347 // zero for arrays.
2348 JVM_QUICK_ENTRY(void, JVM_GetMethodIxExceptionIndexes(JNIEnv *env, jclass cls, jint method_index, unsigned short *exceptions))
2349   JVMWrapper("JVM_GetMethodIxExceptionIndexes");
2350   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2351   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2352   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2353   int length = method->checked_exceptions_length();
2354   if (length > 0) {
2355     CheckedExceptionElement* table= method->checked_exceptions_start();
2356     for (int i = 0; i < length; i++) {
2357       exceptions[i] = table[i].class_cp_index;
2358     }
2359   }
2360 JVM_END
2361 
2362 
2363 JVM_QUICK_ENTRY(jint, JVM_GetMethodIxExceptionsCount(JNIEnv *env, jclass cls, jint method_index))
2364   JVMWrapper("JVM_GetMethodIxExceptionsCount");
2365   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2366   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2367   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2368   return method->checked_exceptions_length();
2369 JVM_END
2370 
2371 
2372 JVM_QUICK_ENTRY(void, JVM_GetMethodIxByteCode(JNIEnv *env, jclass cls, jint method_index, unsigned char *code))
2373   JVMWrapper("JVM_GetMethodIxByteCode");
2374   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2375   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2376   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2377   memcpy(code, method->code_base(), method->code_size());
2378 JVM_END
2379 
2380 
2381 JVM_QUICK_ENTRY(jint, JVM_GetMethodIxByteCodeLength(JNIEnv *env, jclass cls, jint method_index))
2382   JVMWrapper("JVM_GetMethodIxByteCodeLength");
2383   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2384   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2385   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2386   return method->code_size();
2387 JVM_END
2388 
2389 
2390 JVM_QUICK_ENTRY(void, JVM_GetMethodIxExceptionTableEntry(JNIEnv *env, jclass cls, jint method_index, jint entry_index, JVM_ExceptionTableEntryType *entry))
2391   JVMWrapper("JVM_GetMethodIxExceptionTableEntry");
2392   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2393   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2394   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2395   ExceptionTable extable(method);
2396   entry->start_pc   = extable.start_pc(entry_index);
2397   entry->end_pc     = extable.end_pc(entry_index);
2398   entry->handler_pc = extable.handler_pc(entry_index);
2399   entry->catchType  = extable.catch_type_index(entry_index);
2400 JVM_END
2401 
2402 
2403 JVM_QUICK_ENTRY(jint, JVM_GetMethodIxExceptionTableLength(JNIEnv *env, jclass cls, int method_index))
2404   JVMWrapper("JVM_GetMethodIxExceptionTableLength");
2405   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2406   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2407   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2408   return method->exception_table_length();
2409 JVM_END
2410 
2411 
2412 JVM_QUICK_ENTRY(jint, JVM_GetMethodIxModifiers(JNIEnv *env, jclass cls, int method_index))
2413   JVMWrapper("JVM_GetMethodIxModifiers");
2414   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2415   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2416   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2417   return method->access_flags().as_int() & JVM_RECOGNIZED_METHOD_MODIFIERS;
2418 JVM_END
2419 
2420 
2421 JVM_QUICK_ENTRY(jint, JVM_GetFieldIxModifiers(JNIEnv *env, jclass cls, int field_index))
2422   JVMWrapper("JVM_GetFieldIxModifiers");
2423   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2424   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2425   return InstanceKlass::cast(k)->field_access_flags(field_index) & JVM_RECOGNIZED_FIELD_MODIFIERS;
2426 JVM_END
2427 
2428 
2429 JVM_QUICK_ENTRY(jint, JVM_GetMethodIxLocalsCount(JNIEnv *env, jclass cls, int method_index))
2430   JVMWrapper("JVM_GetMethodIxLocalsCount");
2431   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2432   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2433   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2434   return method->max_locals();
2435 JVM_END
2436 
2437 
2438 JVM_QUICK_ENTRY(jint, JVM_GetMethodIxArgsSize(JNIEnv *env, jclass cls, int method_index))
2439   JVMWrapper("JVM_GetMethodIxArgsSize");
2440   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2441   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2442   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2443   return method->size_of_parameters();
2444 JVM_END
2445 
2446 
2447 JVM_QUICK_ENTRY(jint, JVM_GetMethodIxMaxStack(JNIEnv *env, jclass cls, int method_index))
2448   JVMWrapper("JVM_GetMethodIxMaxStack");
2449   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2450   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2451   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2452   return method->verifier_max_stack();
2453 JVM_END
2454 
2455 
2456 JVM_QUICK_ENTRY(jboolean, JVM_IsConstructorIx(JNIEnv *env, jclass cls, int method_index))
2457   JVMWrapper("JVM_IsConstructorIx");
2458   ResourceMark rm(THREAD);
2459   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2460   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2461   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2462   return method->name() == vmSymbols::object_initializer_name();
2463 JVM_END
2464 
2465 
2466 JVM_QUICK_ENTRY(jboolean, JVM_IsVMGeneratedMethodIx(JNIEnv *env, jclass cls, int method_index))
2467   JVMWrapper("JVM_IsVMGeneratedMethodIx");
2468   ResourceMark rm(THREAD);
2469   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2470   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2471   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2472   return method->is_overpass();
2473 JVM_END
2474 
2475 JVM_ENTRY(const char*, JVM_GetMethodIxNameUTF(JNIEnv *env, jclass cls, jint method_index))
2476   JVMWrapper("JVM_GetMethodIxIxUTF");
2477   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2478   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2479   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2480   return method->name()->as_utf8();
2481 JVM_END
2482 
2483 
2484 JVM_ENTRY(const char*, JVM_GetMethodIxSignatureUTF(JNIEnv *env, jclass cls, jint method_index))
2485   JVMWrapper("JVM_GetMethodIxSignatureUTF");
2486   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2487   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2488   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2489   return method->signature()->as_utf8();
2490 JVM_END
2491 
2492 /**
2493  * All of these JVM_GetCP-xxx methods are used by the old verifier to
2494  * read entries in the constant pool.  Since the old verifier always
2495  * works on a copy of the code, it will not see any rewriting that
2496  * may possibly occur in the middle of verification.  So it is important
2497  * that nothing it calls tries to use the cpCache instead of the raw
2498  * constant pool, so we must use cp->uncached_x methods when appropriate.
2499  */
2500 JVM_ENTRY(const char*, JVM_GetCPFieldNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2501   JVMWrapper("JVM_GetCPFieldNameUTF");
2502   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2503   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2504   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2505   switch (cp->tag_at(cp_index).value()) {
2506     case JVM_CONSTANT_Fieldref:
2507       return cp->uncached_name_ref_at(cp_index)->as_utf8();
2508     default:
2509       fatal("JVM_GetCPFieldNameUTF: illegal constant");
2510   }
2511   ShouldNotReachHere();
2512   return NULL;
2513 JVM_END
2514 
2515 
2516 JVM_ENTRY(const char*, JVM_GetCPMethodNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2517   JVMWrapper("JVM_GetCPMethodNameUTF");
2518   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2519   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2520   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2521   switch (cp->tag_at(cp_index).value()) {
2522     case JVM_CONSTANT_InterfaceMethodref:
2523     case JVM_CONSTANT_Methodref:
2524       return cp->uncached_name_ref_at(cp_index)->as_utf8();
2525     default:
2526       fatal("JVM_GetCPMethodNameUTF: illegal constant");
2527   }
2528   ShouldNotReachHere();
2529   return NULL;
2530 JVM_END
2531 
2532 
2533 JVM_ENTRY(const char*, JVM_GetCPMethodSignatureUTF(JNIEnv *env, jclass cls, jint cp_index))
2534   JVMWrapper("JVM_GetCPMethodSignatureUTF");
2535   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2536   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2537   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2538   switch (cp->tag_at(cp_index).value()) {
2539     case JVM_CONSTANT_InterfaceMethodref:
2540     case JVM_CONSTANT_Methodref:
2541       return cp->uncached_signature_ref_at(cp_index)->as_utf8();
2542     default:
2543       fatal("JVM_GetCPMethodSignatureUTF: illegal constant");
2544   }
2545   ShouldNotReachHere();
2546   return NULL;
2547 JVM_END
2548 
2549 
2550 JVM_ENTRY(const char*, JVM_GetCPFieldSignatureUTF(JNIEnv *env, jclass cls, jint cp_index))
2551   JVMWrapper("JVM_GetCPFieldSignatureUTF");
2552   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2553   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2554   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2555   switch (cp->tag_at(cp_index).value()) {
2556     case JVM_CONSTANT_Fieldref:
2557       return cp->uncached_signature_ref_at(cp_index)->as_utf8();
2558     default:
2559       fatal("JVM_GetCPFieldSignatureUTF: illegal constant");
2560   }
2561   ShouldNotReachHere();
2562   return NULL;
2563 JVM_END
2564 
2565 
2566 JVM_ENTRY(const char*, JVM_GetCPClassNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2567   JVMWrapper("JVM_GetCPClassNameUTF");
2568   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2569   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2570   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2571   Symbol* classname = cp->klass_name_at(cp_index);
2572   return classname->as_utf8();
2573 JVM_END
2574 
2575 
2576 JVM_ENTRY(const char*, JVM_GetCPFieldClassNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2577   JVMWrapper("JVM_GetCPFieldClassNameUTF");
2578   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2579   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2580   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2581   switch (cp->tag_at(cp_index).value()) {
2582     case JVM_CONSTANT_Fieldref: {
2583       int class_index = cp->uncached_klass_ref_index_at(cp_index);
2584       Symbol* classname = cp->klass_name_at(class_index);
2585       return classname->as_utf8();
2586     }
2587     default:
2588       fatal("JVM_GetCPFieldClassNameUTF: illegal constant");
2589   }
2590   ShouldNotReachHere();
2591   return NULL;
2592 JVM_END
2593 
2594 
2595 JVM_ENTRY(const char*, JVM_GetCPMethodClassNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2596   JVMWrapper("JVM_GetCPMethodClassNameUTF");
2597   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2598   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2599   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2600   switch (cp->tag_at(cp_index).value()) {
2601     case JVM_CONSTANT_Methodref:
2602     case JVM_CONSTANT_InterfaceMethodref: {
2603       int class_index = cp->uncached_klass_ref_index_at(cp_index);
2604       Symbol* classname = cp->klass_name_at(class_index);
2605       return classname->as_utf8();
2606     }
2607     default:
2608       fatal("JVM_GetCPMethodClassNameUTF: illegal constant");
2609   }
2610   ShouldNotReachHere();
2611   return NULL;
2612 JVM_END
2613 
2614 
2615 JVM_ENTRY(jint, JVM_GetCPFieldModifiers(JNIEnv *env, jclass cls, int cp_index, jclass called_cls))
2616   JVMWrapper("JVM_GetCPFieldModifiers");
2617   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2618   Klass* k_called = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(called_cls));
2619   k        = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2620   k_called = JvmtiThreadState::class_to_verify_considering_redefinition(k_called, thread);
2621   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2622   ConstantPool* cp_called = InstanceKlass::cast(k_called)->constants();
2623   switch (cp->tag_at(cp_index).value()) {
2624     case JVM_CONSTANT_Fieldref: {
2625       Symbol* name      = cp->uncached_name_ref_at(cp_index);
2626       Symbol* signature = cp->uncached_signature_ref_at(cp_index);
2627       InstanceKlass* ik = InstanceKlass::cast(k_called);
2628       for (JavaFieldStream fs(ik); !fs.done(); fs.next()) {
2629         if (fs.name() == name && fs.signature() == signature) {
2630           return fs.access_flags().as_short() & JVM_RECOGNIZED_FIELD_MODIFIERS;
2631         }
2632       }
2633       return -1;
2634     }
2635     default:
2636       fatal("JVM_GetCPFieldModifiers: illegal constant");
2637   }
2638   ShouldNotReachHere();
2639   return 0;
2640 JVM_END
2641 
2642 
2643 JVM_QUICK_ENTRY(jint, JVM_GetCPMethodModifiers(JNIEnv *env, jclass cls, int cp_index, jclass called_cls))
2644   JVMWrapper("JVM_GetCPMethodModifiers");
2645   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2646   Klass* k_called = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(called_cls));
2647   k        = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2648   k_called = JvmtiThreadState::class_to_verify_considering_redefinition(k_called, thread);
2649   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2650   switch (cp->tag_at(cp_index).value()) {
2651     case JVM_CONSTANT_Methodref:
2652     case JVM_CONSTANT_InterfaceMethodref: {
2653       Symbol* name      = cp->uncached_name_ref_at(cp_index);
2654       Symbol* signature = cp->uncached_signature_ref_at(cp_index);
2655       Array<Method*>* methods = InstanceKlass::cast(k_called)->methods();
2656       int methods_count = methods->length();
2657       for (int i = 0; i < methods_count; i++) {
2658         Method* method = methods->at(i);
2659         if (method->name() == name && method->signature() == signature) {
2660             return method->access_flags().as_int() & JVM_RECOGNIZED_METHOD_MODIFIERS;
2661         }
2662       }
2663       return -1;
2664     }
2665     default:
2666       fatal("JVM_GetCPMethodModifiers: illegal constant");
2667   }
2668   ShouldNotReachHere();
2669   return 0;
2670 JVM_END
2671 
2672 
2673 // Misc //////////////////////////////////////////////////////////////////////////////////////////////
2674 
2675 JVM_LEAF(void, JVM_ReleaseUTF(const char *utf))
2676   // So long as UTF8::convert_to_utf8 returns resource strings, we don't have to do anything
2677 JVM_END
2678 
2679 
2680 JVM_ENTRY(jboolean, JVM_IsSameClassPackage(JNIEnv *env, jclass class1, jclass class2))
2681   JVMWrapper("JVM_IsSameClassPackage");
2682   oop class1_mirror = JNIHandles::resolve_non_null(class1);
2683   oop class2_mirror = JNIHandles::resolve_non_null(class2);
2684   Klass* klass1 = java_lang_Class::as_Klass(class1_mirror);
2685   Klass* klass2 = java_lang_Class::as_Klass(class2_mirror);
2686   return (jboolean) Reflection::is_same_class_package(klass1, klass2);
2687 JVM_END
2688 
2689 // Printing support //////////////////////////////////////////////////
2690 extern "C" {
2691 
2692 ATTRIBUTE_PRINTF(3, 0)
2693 int jio_vsnprintf(char *str, size_t count, const char *fmt, va_list args) {
2694   // Reject count values that are negative signed values converted to
2695   // unsigned; see bug 4399518, 4417214
2696   if ((intptr_t)count <= 0) return -1;
2697 
2698   int result = os::vsnprintf(str, count, fmt, args);
2699   if (result > 0 && (size_t)result >= count) {
2700     result = -1;
2701   }
2702 
2703   return result;
2704 }
2705 
2706 ATTRIBUTE_PRINTF(3, 4)
2707 int jio_snprintf(char *str, size_t count, const char *fmt, ...) {
2708   va_list args;
2709   int len;
2710   va_start(args, fmt);
2711   len = jio_vsnprintf(str, count, fmt, args);
2712   va_end(args);
2713   return len;
2714 }
2715 
2716 ATTRIBUTE_PRINTF(2, 3)
2717 int jio_fprintf(FILE* f, const char *fmt, ...) {
2718   int len;
2719   va_list args;
2720   va_start(args, fmt);
2721   len = jio_vfprintf(f, fmt, args);
2722   va_end(args);
2723   return len;
2724 }
2725 
2726 ATTRIBUTE_PRINTF(2, 0)
2727 int jio_vfprintf(FILE* f, const char *fmt, va_list args) {
2728   if (Arguments::vfprintf_hook() != NULL) {
2729      return Arguments::vfprintf_hook()(f, fmt, args);
2730   } else {
2731     return vfprintf(f, fmt, args);
2732   }
2733 }
2734 
2735 ATTRIBUTE_PRINTF(1, 2)
2736 JNIEXPORT int jio_printf(const char *fmt, ...) {
2737   int len;
2738   va_list args;
2739   va_start(args, fmt);
2740   len = jio_vfprintf(defaultStream::output_stream(), fmt, args);
2741   va_end(args);
2742   return len;
2743 }
2744 
2745 // HotSpot specific jio method
2746 void jio_print(const char* s, size_t len) {
2747   // Try to make this function as atomic as possible.
2748   if (Arguments::vfprintf_hook() != NULL) {
2749     jio_fprintf(defaultStream::output_stream(), "%.*s", (int)len, s);
2750   } else {
2751     // Make an unused local variable to avoid warning from gcc 4.x compiler.
2752     size_t count = ::write(defaultStream::output_fd(), s, (int)len);
2753   }
2754 }
2755 
2756 } // Extern C
2757 
2758 // java.lang.Thread //////////////////////////////////////////////////////////////////////////////
2759 
2760 // In most of the JVM thread support functions we need to access the
2761 // thread through a ThreadsListHandle to prevent it from exiting and
2762 // being reclaimed while we try to operate on it. The exceptions to this
2763 // rule are when operating on the current thread, or if the monitor of
2764 // the target java.lang.Thread is locked at the Java level - in both
2765 // cases the target cannot exit.
2766 
2767 static void thread_entry(JavaThread* thread, TRAPS) {
2768   HandleMark hm(THREAD);
2769   Handle obj(THREAD, thread->threadObj());
2770   JavaValue result(T_VOID);
2771   JavaCalls::call_virtual(&result,
2772                           obj,
2773                           SystemDictionary::Thread_klass(),
2774                           vmSymbols::run_method_name(),
2775                           vmSymbols::void_method_signature(),
2776                           THREAD);
2777 }
2778 
2779 
2780 JVM_ENTRY(void, JVM_StartThread(JNIEnv* env, jobject jthread))
2781   JVMWrapper("JVM_StartThread");
2782   JavaThread *native_thread = NULL;
2783 
2784   // We cannot hold the Threads_lock when we throw an exception,
2785   // due to rank ordering issues. Example:  we might need to grab the
2786   // Heap_lock while we construct the exception.
2787   bool throw_illegal_thread_state = false;
2788 
2789   // We must release the Threads_lock before we can post a jvmti event
2790   // in Thread::start.
2791   {
2792     // Ensure that the C++ Thread and OSThread structures aren't freed before
2793     // we operate.
2794     MutexLocker mu(Threads_lock);
2795 
2796     // Since JDK 5 the java.lang.Thread threadStatus is used to prevent
2797     // re-starting an already started thread, so we should usually find
2798     // that the JavaThread is null. However for a JNI attached thread
2799     // there is a small window between the Thread object being created
2800     // (with its JavaThread set) and the update to its threadStatus, so we
2801     // have to check for this
2802     if (java_lang_Thread::thread(JNIHandles::resolve_non_null(jthread)) != NULL) {
2803       throw_illegal_thread_state = true;
2804     } else {
2805       // We could also check the stillborn flag to see if this thread was already stopped, but
2806       // for historical reasons we let the thread detect that itself when it starts running
2807 
2808       jlong size =
2809              java_lang_Thread::stackSize(JNIHandles::resolve_non_null(jthread));
2810       // Allocate the C++ Thread structure and create the native thread.  The
2811       // stack size retrieved from java is 64-bit signed, but the constructor takes
2812       // size_t (an unsigned type), which may be 32 or 64-bit depending on the platform.
2813       //  - Avoid truncating on 32-bit platforms if size is greater than UINT_MAX.
2814       //  - Avoid passing negative values which would result in really large stacks.
2815       NOT_LP64(if (size > SIZE_MAX) size = SIZE_MAX;)
2816       size_t sz = size > 0 ? (size_t) size : 0;
2817       native_thread = new JavaThread(&thread_entry, sz);
2818 
2819       // At this point it may be possible that no osthread was created for the
2820       // JavaThread due to lack of memory. Check for this situation and throw
2821       // an exception if necessary. Eventually we may want to change this so
2822       // that we only grab the lock if the thread was created successfully -
2823       // then we can also do this check and throw the exception in the
2824       // JavaThread constructor.
2825       if (native_thread->osthread() != NULL) {
2826         // Note: the current thread is not being used within "prepare".
2827         native_thread->prepare(jthread);
2828       }
2829     }
2830   }
2831 
2832   if (throw_illegal_thread_state) {
2833     THROW(vmSymbols::java_lang_IllegalThreadStateException());
2834   }
2835 
2836   assert(native_thread != NULL, "Starting null thread?");
2837 
2838   if (native_thread->osthread() == NULL) {
2839     // No one should hold a reference to the 'native_thread'.
2840     native_thread->smr_delete();
2841     if (JvmtiExport::should_post_resource_exhausted()) {
2842       JvmtiExport::post_resource_exhausted(
2843         JVMTI_RESOURCE_EXHAUSTED_OOM_ERROR | JVMTI_RESOURCE_EXHAUSTED_THREADS,
2844         os::native_thread_creation_failed_msg());
2845     }
2846     THROW_MSG(vmSymbols::java_lang_OutOfMemoryError(),
2847               os::native_thread_creation_failed_msg());
2848   }
2849 
2850   Thread::start(native_thread);
2851 
2852 JVM_END
2853 
2854 
2855 // JVM_Stop is implemented using a VM_Operation, so threads are forced to safepoints
2856 // before the quasi-asynchronous exception is delivered.  This is a little obtrusive,
2857 // but is thought to be reliable and simple. In the case, where the receiver is the
2858 // same thread as the sender, no VM_Operation is needed.
2859 JVM_ENTRY(void, JVM_StopThread(JNIEnv* env, jobject jthread, jobject throwable))
2860   JVMWrapper("JVM_StopThread");
2861 
2862   // A nested ThreadsListHandle will grab the Threads_lock so create
2863   // tlh before we resolve throwable.
2864   ThreadsListHandle tlh(thread);
2865   oop java_throwable = JNIHandles::resolve(throwable);
2866   if (java_throwable == NULL) {
2867     THROW(vmSymbols::java_lang_NullPointerException());
2868   }
2869   oop java_thread = NULL;
2870   JavaThread* receiver = NULL;
2871   bool is_alive = tlh.cv_internal_thread_to_JavaThread(jthread, &receiver, &java_thread);
2872   Events::log_exception(thread,
2873                         "JVM_StopThread thread JavaThread " INTPTR_FORMAT " as oop " INTPTR_FORMAT " [exception " INTPTR_FORMAT "]",
2874                         p2i(receiver), p2i((address)java_thread), p2i(throwable));
2875 
2876   if (is_alive) {
2877     // jthread refers to a live JavaThread.
2878     if (thread == receiver) {
2879       // Exception is getting thrown at self so no VM_Operation needed.
2880       THROW_OOP(java_throwable);
2881     } else {
2882       // Use a VM_Operation to throw the exception.
2883       Thread::send_async_exception(java_thread, java_throwable);
2884     }
2885   } else {
2886     // Either:
2887     // - target thread has not been started before being stopped, or
2888     // - target thread already terminated
2889     // We could read the threadStatus to determine which case it is
2890     // but that is overkill as it doesn't matter. We must set the
2891     // stillborn flag for the first case, and if the thread has already
2892     // exited setting this flag has no effect.
2893     java_lang_Thread::set_stillborn(java_thread);
2894   }
2895 JVM_END
2896 
2897 
2898 JVM_ENTRY(jboolean, JVM_IsThreadAlive(JNIEnv* env, jobject jthread))
2899   JVMWrapper("JVM_IsThreadAlive");
2900 
2901   oop thread_oop = JNIHandles::resolve_non_null(jthread);
2902   return java_lang_Thread::is_alive(thread_oop);
2903 JVM_END
2904 
2905 
2906 JVM_ENTRY(void, JVM_SuspendThread(JNIEnv* env, jobject jthread))
2907   JVMWrapper("JVM_SuspendThread");
2908 
2909   ThreadsListHandle tlh(thread);
2910   JavaThread* receiver = NULL;
2911   bool is_alive = tlh.cv_internal_thread_to_JavaThread(jthread, &receiver, NULL);
2912   if (is_alive) {
2913     // jthread refers to a live JavaThread.
2914     {
2915       MutexLockerEx ml(receiver->SR_lock(), Mutex::_no_safepoint_check_flag);
2916       if (receiver->is_external_suspend()) {
2917         // Don't allow nested external suspend requests. We can't return
2918         // an error from this interface so just ignore the problem.
2919         return;
2920       }
2921       if (receiver->is_exiting()) { // thread is in the process of exiting
2922         return;
2923       }
2924       receiver->set_external_suspend();
2925     }
2926 
2927     // java_suspend() will catch threads in the process of exiting
2928     // and will ignore them.
2929     receiver->java_suspend();
2930 
2931     // It would be nice to have the following assertion in all the
2932     // time, but it is possible for a racing resume request to have
2933     // resumed this thread right after we suspended it. Temporarily
2934     // enable this assertion if you are chasing a different kind of
2935     // bug.
2936     //
2937     // assert(java_lang_Thread::thread(receiver->threadObj()) == NULL ||
2938     //   receiver->is_being_ext_suspended(), "thread is not suspended");
2939   }
2940 JVM_END
2941 
2942 
2943 JVM_ENTRY(void, JVM_ResumeThread(JNIEnv* env, jobject jthread))
2944   JVMWrapper("JVM_ResumeThread");
2945 
2946   ThreadsListHandle tlh(thread);
2947   JavaThread* receiver = NULL;
2948   bool is_alive = tlh.cv_internal_thread_to_JavaThread(jthread, &receiver, NULL);
2949   if (is_alive) {
2950     // jthread refers to a live JavaThread.
2951 
2952     // This is the original comment for this Threads_lock grab:
2953     //   We need to *always* get the threads lock here, since this operation cannot be allowed during
2954     //   a safepoint. The safepoint code relies on suspending a thread to examine its state. If other
2955     //   threads randomly resumes threads, then a thread might not be suspended when the safepoint code
2956     //   looks at it.
2957     //
2958     // The above comment dates back to when we had both internal and
2959     // external suspend APIs that shared a common underlying mechanism.
2960     // External suspend is now entirely cooperative and doesn't share
2961     // anything with internal suspend. That said, there are some
2962     // assumptions in the VM that an external resume grabs the
2963     // Threads_lock. We can't drop the Threads_lock grab here until we
2964     // resolve the assumptions that exist elsewhere.
2965     //
2966     MutexLocker ml(Threads_lock);
2967     receiver->java_resume();
2968   }
2969 JVM_END
2970 
2971 
2972 JVM_ENTRY(void, JVM_SetThreadPriority(JNIEnv* env, jobject jthread, jint prio))
2973   JVMWrapper("JVM_SetThreadPriority");
2974 
2975   ThreadsListHandle tlh(thread);
2976   oop java_thread = NULL;
2977   JavaThread* receiver = NULL;
2978   bool is_alive = tlh.cv_internal_thread_to_JavaThread(jthread, &receiver, &java_thread);
2979   java_lang_Thread::set_priority(java_thread, (ThreadPriority)prio);
2980 
2981   if (is_alive) {
2982     // jthread refers to a live JavaThread.
2983     Thread::set_priority(receiver, (ThreadPriority)prio);
2984   }
2985   // Implied else: If the JavaThread hasn't started yet, then the
2986   // priority set in the java.lang.Thread object above will be pushed
2987   // down when it does start.
2988 JVM_END
2989 
2990 
2991 JVM_ENTRY(void, JVM_Yield(JNIEnv *env, jclass threadClass))
2992   JVMWrapper("JVM_Yield");
2993   if (os::dont_yield()) return;
2994   HOTSPOT_THREAD_YIELD();
2995   os::naked_yield();
2996 JVM_END
2997 
2998 static void post_thread_sleep_event(EventThreadSleep* event, jlong millis) {
2999   assert(event != NULL, "invariant");
3000   assert(event->should_commit(), "invariant");
3001   event->set_time(millis);
3002   event->commit();
3003 }
3004 
3005 JVM_ENTRY(void, JVM_Sleep(JNIEnv* env, jclass threadClass, jlong millis))
3006   JVMWrapper("JVM_Sleep");
3007 
3008   if (millis < 0) {
3009     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "timeout value is negative");
3010   }
3011 
3012   if (Thread::is_interrupted (THREAD, true) && !HAS_PENDING_EXCEPTION) {
3013     THROW_MSG(vmSymbols::java_lang_InterruptedException(), "sleep interrupted");
3014   }
3015 
3016   // Save current thread state and restore it at the end of this block.
3017   // And set new thread state to SLEEPING.
3018   JavaThreadSleepState jtss(thread);
3019 
3020   HOTSPOT_THREAD_SLEEP_BEGIN(millis);
3021   EventThreadSleep event;
3022 
3023   if (millis == 0) {
3024     os::naked_yield();
3025   } else {
3026     ThreadState old_state = thread->osthread()->get_state();
3027     thread->osthread()->set_state(SLEEPING);
3028     if (os::sleep(thread, millis, true) == OS_INTRPT) {
3029       // An asynchronous exception (e.g., ThreadDeathException) could have been thrown on
3030       // us while we were sleeping. We do not overwrite those.
3031       if (!HAS_PENDING_EXCEPTION) {
3032         if (event.should_commit()) {
3033           post_thread_sleep_event(&event, millis);
3034         }
3035         HOTSPOT_THREAD_SLEEP_END(1);
3036 
3037         // TODO-FIXME: THROW_MSG returns which means we will not call set_state()
3038         // to properly restore the thread state.  That's likely wrong.
3039         THROW_MSG(vmSymbols::java_lang_InterruptedException(), "sleep interrupted");
3040       }
3041     }
3042     thread->osthread()->set_state(old_state);
3043   }
3044   if (event.should_commit()) {
3045     post_thread_sleep_event(&event, millis);
3046   }
3047   HOTSPOT_THREAD_SLEEP_END(0);
3048 JVM_END
3049 
3050 JVM_ENTRY(jobject, JVM_CurrentThread(JNIEnv* env, jclass threadClass))
3051   JVMWrapper("JVM_CurrentThread");
3052   oop jthread = thread->threadObj();
3053   assert (thread != NULL, "no current thread!");
3054   return JNIHandles::make_local(env, jthread);
3055 JVM_END
3056 
3057 
3058 JVM_ENTRY(jint, JVM_CountStackFrames(JNIEnv* env, jobject jthread))
3059   JVMWrapper("JVM_CountStackFrames");
3060 
3061   uint32_t debug_bits = 0;
3062   ThreadsListHandle tlh(thread);
3063   JavaThread* receiver = NULL;
3064   bool is_alive = tlh.cv_internal_thread_to_JavaThread(jthread, &receiver, NULL);
3065   int count = 0;
3066   if (is_alive) {
3067     // jthread refers to a live JavaThread.
3068     if (receiver->is_thread_fully_suspended(true /* wait for suspend completion */, &debug_bits)) {
3069       // Count all java activation, i.e., number of vframes.
3070       for (vframeStream vfst(receiver); !vfst.at_end(); vfst.next()) {
3071         // Native frames are not counted.
3072         if (!vfst.method()->is_native()) count++;
3073       }
3074     } else {
3075       THROW_MSG_0(vmSymbols::java_lang_IllegalThreadStateException(),
3076                   "this thread is not suspended");
3077     }
3078   }
3079   // Implied else: if JavaThread is not alive simply return a count of 0.
3080 
3081   return count;
3082 JVM_END
3083 
3084 
3085 JVM_ENTRY(void, JVM_Interrupt(JNIEnv* env, jobject jthread))
3086   JVMWrapper("JVM_Interrupt");
3087 
3088   ThreadsListHandle tlh(thread);
3089   JavaThread* receiver = NULL;
3090   bool is_alive = tlh.cv_internal_thread_to_JavaThread(jthread, &receiver, NULL);
3091   if (is_alive) {
3092     // jthread refers to a live JavaThread.
3093     Thread::interrupt(receiver);
3094   }
3095 JVM_END
3096 
3097 
3098 JVM_QUICK_ENTRY(jboolean, JVM_IsInterrupted(JNIEnv* env, jobject jthread, jboolean clear_interrupted))
3099   JVMWrapper("JVM_IsInterrupted");
3100 
3101   ThreadsListHandle tlh(thread);
3102   JavaThread* receiver = NULL;
3103   bool is_alive = tlh.cv_internal_thread_to_JavaThread(jthread, &receiver, NULL);
3104   if (is_alive) {
3105     // jthread refers to a live JavaThread.
3106     return (jboolean) Thread::is_interrupted(receiver, clear_interrupted != 0);
3107   } else {
3108     return JNI_FALSE;
3109   }
3110 JVM_END
3111 
3112 
3113 // Return true iff the current thread has locked the object passed in
3114 
3115 JVM_ENTRY(jboolean, JVM_HoldsLock(JNIEnv* env, jclass threadClass, jobject obj))
3116   JVMWrapper("JVM_HoldsLock");
3117   assert(THREAD->is_Java_thread(), "sanity check");
3118   if (obj == NULL) {
3119     THROW_(vmSymbols::java_lang_NullPointerException(), JNI_FALSE);
3120   }
3121   Handle h_obj(THREAD, JNIHandles::resolve(obj));
3122   return ObjectSynchronizer::current_thread_holds_lock((JavaThread*)THREAD, h_obj);
3123 JVM_END
3124 
3125 
3126 JVM_ENTRY(void, JVM_DumpAllStacks(JNIEnv* env, jclass))
3127   JVMWrapper("JVM_DumpAllStacks");
3128   VM_PrintThreads op;
3129   VMThread::execute(&op);
3130   if (JvmtiExport::should_post_data_dump()) {
3131     JvmtiExport::post_data_dump();
3132   }
3133 JVM_END
3134 
3135 JVM_ENTRY(void, JVM_SetNativeThreadName(JNIEnv* env, jobject jthread, jstring name))
3136   JVMWrapper("JVM_SetNativeThreadName");
3137 
3138   // We don't use a ThreadsListHandle here because the current thread
3139   // must be alive.
3140   oop java_thread = JNIHandles::resolve_non_null(jthread);
3141   JavaThread* thr = java_lang_Thread::thread(java_thread);
3142   if (thread == thr && !thr->has_attached_via_jni()) {
3143     // Thread naming is only supported for the current thread and
3144     // we don't set the name of an attached thread to avoid stepping
3145     // on other programs.
3146     ResourceMark rm(thread);
3147     const char *thread_name = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(name));
3148     os::set_native_thread_name(thread_name);
3149   }
3150 JVM_END
3151 
3152 // java.lang.SecurityManager ///////////////////////////////////////////////////////////////////////
3153 
3154 JVM_ENTRY(jobjectArray, JVM_GetClassContext(JNIEnv *env))
3155   JVMWrapper("JVM_GetClassContext");
3156   ResourceMark rm(THREAD);
3157   JvmtiVMObjectAllocEventCollector oam;
3158   vframeStream vfst(thread);
3159 
3160   if (SystemDictionary::reflect_CallerSensitive_klass() != NULL) {
3161     // This must only be called from SecurityManager.getClassContext
3162     Method* m = vfst.method();
3163     if (!(m->method_holder() == SystemDictionary::SecurityManager_klass() &&
3164           m->name()          == vmSymbols::getClassContext_name() &&
3165           m->signature()     == vmSymbols::void_class_array_signature())) {
3166       THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), "JVM_GetClassContext must only be called from SecurityManager.getClassContext");
3167     }
3168   }
3169 
3170   // Collect method holders
3171   GrowableArray<Klass*>* klass_array = new GrowableArray<Klass*>();
3172   for (; !vfst.at_end(); vfst.security_next()) {
3173     Method* m = vfst.method();
3174     // Native frames are not returned
3175     if (!m->is_ignored_by_security_stack_walk() && !m->is_native()) {
3176       Klass* holder = m->method_holder();
3177       assert(holder->is_klass(), "just checking");
3178       klass_array->append(holder);
3179     }
3180   }
3181 
3182   // Create result array of type [Ljava/lang/Class;
3183   objArrayOop result = oopFactory::new_objArray(SystemDictionary::Class_klass(), klass_array->length(), CHECK_NULL);
3184   // Fill in mirrors corresponding to method holders
3185   for (int i = 0; i < klass_array->length(); i++) {
3186     result->obj_at_put(i, klass_array->at(i)->java_mirror());
3187   }
3188 
3189   return (jobjectArray) JNIHandles::make_local(env, result);
3190 JVM_END
3191 
3192 
3193 // java.lang.Package ////////////////////////////////////////////////////////////////
3194 
3195 
3196 JVM_ENTRY(jstring, JVM_GetSystemPackage(JNIEnv *env, jstring name))
3197   JVMWrapper("JVM_GetSystemPackage");
3198   ResourceMark rm(THREAD);
3199   JvmtiVMObjectAllocEventCollector oam;
3200   char* str = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(name));
3201   oop result = ClassLoader::get_system_package(str, CHECK_NULL);
3202   return (jstring) JNIHandles::make_local(result);
3203 JVM_END
3204 
3205 
3206 JVM_ENTRY(jobjectArray, JVM_GetSystemPackages(JNIEnv *env))
3207   JVMWrapper("JVM_GetSystemPackages");
3208   JvmtiVMObjectAllocEventCollector oam;
3209   objArrayOop result = ClassLoader::get_system_packages(CHECK_NULL);
3210   return (jobjectArray) JNIHandles::make_local(result);
3211 JVM_END
3212 
3213 
3214 // java.lang.ref.Reference ///////////////////////////////////////////////////////////////
3215 
3216 
3217 JVM_ENTRY(jobject, JVM_GetAndClearReferencePendingList(JNIEnv* env))
3218   JVMWrapper("JVM_GetAndClearReferencePendingList");
3219 
3220   MonitorLockerEx ml(Heap_lock);
3221   oop ref = Universe::reference_pending_list();
3222   if (ref != NULL) {
3223     Universe::set_reference_pending_list(NULL);
3224   }
3225   return JNIHandles::make_local(env, ref);
3226 JVM_END
3227 
3228 JVM_ENTRY(jboolean, JVM_HasReferencePendingList(JNIEnv* env))
3229   JVMWrapper("JVM_HasReferencePendingList");
3230   MonitorLockerEx ml(Heap_lock);
3231   return Universe::has_reference_pending_list();
3232 JVM_END
3233 
3234 JVM_ENTRY(void, JVM_WaitForReferencePendingList(JNIEnv* env))
3235   JVMWrapper("JVM_WaitForReferencePendingList");
3236   MonitorLockerEx ml(Heap_lock);
3237   while (!Universe::has_reference_pending_list()) {
3238     ml.wait();
3239   }
3240 JVM_END
3241 
3242 
3243 // ObjectInputStream ///////////////////////////////////////////////////////////////
3244 
3245 // Return the first user-defined class loader up the execution stack, or null
3246 // if only code from the bootstrap or platform class loader is on the stack.
3247 
3248 JVM_ENTRY(jobject, JVM_LatestUserDefinedLoader(JNIEnv *env))
3249   for (vframeStream vfst(thread); !vfst.at_end(); vfst.next()) {
3250     vfst.skip_reflection_related_frames(); // Only needed for 1.4 reflection
3251     oop loader = vfst.method()->method_holder()->class_loader();
3252     if (loader != NULL && !SystemDictionary::is_platform_class_loader(loader)) {
3253       return JNIHandles::make_local(env, loader);
3254     }
3255   }
3256   return NULL;
3257 JVM_END
3258 
3259 
3260 // Array ///////////////////////////////////////////////////////////////////////////////////////////
3261 
3262 
3263 // resolve array handle and check arguments
3264 static inline arrayOop check_array(JNIEnv *env, jobject arr, bool type_array_only, TRAPS) {
3265   if (arr == NULL) {
3266     THROW_0(vmSymbols::java_lang_NullPointerException());
3267   }
3268   oop a = JNIHandles::resolve_non_null(arr);
3269   if (!a->is_array()) {
3270     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Argument is not an array");
3271   } else if (type_array_only && !a->is_typeArray()) {
3272     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Argument is not an array of primitive type");
3273   }
3274   return arrayOop(a);
3275 }
3276 
3277 
3278 JVM_ENTRY(jint, JVM_GetArrayLength(JNIEnv *env, jobject arr))
3279   JVMWrapper("JVM_GetArrayLength");
3280   arrayOop a = check_array(env, arr, false, CHECK_0);
3281   return a->length();
3282 JVM_END
3283 
3284 
3285 JVM_ENTRY(jobject, JVM_GetArrayElement(JNIEnv *env, jobject arr, jint index))
3286   JVMWrapper("JVM_Array_Get");
3287   JvmtiVMObjectAllocEventCollector oam;
3288   arrayOop a = check_array(env, arr, false, CHECK_NULL);
3289   jvalue value;
3290   BasicType type = Reflection::array_get(&value, a, index, CHECK_NULL);
3291   oop box = Reflection::box(&value, type, CHECK_NULL);
3292   return JNIHandles::make_local(env, box);
3293 JVM_END
3294 
3295 
3296 JVM_ENTRY(jvalue, JVM_GetPrimitiveArrayElement(JNIEnv *env, jobject arr, jint index, jint wCode))
3297   JVMWrapper("JVM_GetPrimitiveArrayElement");
3298   jvalue value;
3299   value.i = 0; // to initialize value before getting used in CHECK
3300   arrayOop a = check_array(env, arr, true, CHECK_(value));
3301   assert(a->is_typeArray(), "just checking");
3302   BasicType type = Reflection::array_get(&value, a, index, CHECK_(value));
3303   BasicType wide_type = (BasicType) wCode;
3304   if (type != wide_type) {
3305     Reflection::widen(&value, type, wide_type, CHECK_(value));
3306   }
3307   return value;
3308 JVM_END
3309 
3310 
3311 JVM_ENTRY(void, JVM_SetArrayElement(JNIEnv *env, jobject arr, jint index, jobject val))
3312   JVMWrapper("JVM_SetArrayElement");
3313   arrayOop a = check_array(env, arr, false, CHECK);
3314   oop box = JNIHandles::resolve(val);
3315   jvalue value;
3316   value.i = 0; // to initialize value before getting used in CHECK
3317   BasicType value_type;
3318   if (a->is_objArray()) {
3319     // Make sure we do no unbox e.g. java/lang/Integer instances when storing into an object array
3320     value_type = Reflection::unbox_for_regular_object(box, &value);
3321   } else {
3322     value_type = Reflection::unbox_for_primitive(box, &value, CHECK);
3323   }
3324   Reflection::array_set(&value, a, index, value_type, CHECK);
3325 JVM_END
3326 
3327 
3328 JVM_ENTRY(void, JVM_SetPrimitiveArrayElement(JNIEnv *env, jobject arr, jint index, jvalue v, unsigned char vCode))
3329   JVMWrapper("JVM_SetPrimitiveArrayElement");
3330   arrayOop a = check_array(env, arr, true, CHECK);
3331   assert(a->is_typeArray(), "just checking");
3332   BasicType value_type = (BasicType) vCode;
3333   Reflection::array_set(&v, a, index, value_type, CHECK);
3334 JVM_END
3335 
3336 
3337 JVM_ENTRY(jobject, JVM_NewArray(JNIEnv *env, jclass eltClass, jint length))
3338   JVMWrapper("JVM_NewArray");
3339   JvmtiVMObjectAllocEventCollector oam;
3340   oop element_mirror = JNIHandles::resolve(eltClass);
3341   oop result = Reflection::reflect_new_array(element_mirror, length, CHECK_NULL);
3342   return JNIHandles::make_local(env, result);
3343 JVM_END
3344 
3345 
3346 JVM_ENTRY(jobject, JVM_NewMultiArray(JNIEnv *env, jclass eltClass, jintArray dim))
3347   JVMWrapper("JVM_NewMultiArray");
3348   JvmtiVMObjectAllocEventCollector oam;
3349   arrayOop dim_array = check_array(env, dim, true, CHECK_NULL);
3350   oop element_mirror = JNIHandles::resolve(eltClass);
3351   assert(dim_array->is_typeArray(), "just checking");
3352   oop result = Reflection::reflect_new_multi_array(element_mirror, typeArrayOop(dim_array), CHECK_NULL);
3353   return JNIHandles::make_local(env, result);
3354 JVM_END
3355 
3356 
3357 // Library support ///////////////////////////////////////////////////////////////////////////
3358 
3359 JVM_ENTRY_NO_ENV(void*, JVM_LoadLibrary(const char* name))
3360   //%note jvm_ct
3361   JVMWrapper("JVM_LoadLibrary");
3362   char ebuf[1024];
3363   void *load_result;
3364   {
3365     ThreadToNativeFromVM ttnfvm(thread);
3366     load_result = os::dll_load(name, ebuf, sizeof ebuf);
3367   }
3368   if (load_result == NULL) {
3369     char msg[1024];
3370     jio_snprintf(msg, sizeof msg, "%s: %s", name, ebuf);
3371     // Since 'ebuf' may contain a string encoded using
3372     // platform encoding scheme, we need to pass
3373     // Exceptions::unsafe_to_utf8 to the new_exception method
3374     // as the last argument. See bug 6367357.
3375     Handle h_exception =
3376       Exceptions::new_exception(thread,
3377                                 vmSymbols::java_lang_UnsatisfiedLinkError(),
3378                                 msg, Exceptions::unsafe_to_utf8);
3379 
3380     THROW_HANDLE_0(h_exception);
3381   }
3382   return load_result;
3383 JVM_END
3384 
3385 
3386 JVM_LEAF(void, JVM_UnloadLibrary(void* handle))
3387   JVMWrapper("JVM_UnloadLibrary");
3388   os::dll_unload(handle);
3389 JVM_END
3390 
3391 
3392 JVM_LEAF(void*, JVM_FindLibraryEntry(void* handle, const char* name))
3393   JVMWrapper("JVM_FindLibraryEntry");
3394   return os::dll_lookup(handle, name);
3395 JVM_END
3396 
3397 
3398 // JNI version ///////////////////////////////////////////////////////////////////////////////
3399 
3400 JVM_LEAF(jboolean, JVM_IsSupportedJNIVersion(jint version))
3401   JVMWrapper("JVM_IsSupportedJNIVersion");
3402   return Threads::is_supported_jni_version_including_1_1(version);
3403 JVM_END
3404 
3405 
3406 // String support ///////////////////////////////////////////////////////////////////////////
3407 
3408 JVM_ENTRY(jstring, JVM_InternString(JNIEnv *env, jstring str))
3409   JVMWrapper("JVM_InternString");
3410   JvmtiVMObjectAllocEventCollector oam;
3411   if (str == NULL) return NULL;
3412   oop string = JNIHandles::resolve_non_null(str);
3413   oop result = StringTable::intern(string, CHECK_NULL);
3414   return (jstring) JNIHandles::make_local(env, result);
3415 JVM_END
3416 
3417 
3418 // Raw monitor support //////////////////////////////////////////////////////////////////////
3419 
3420 // The lock routine below calls lock_without_safepoint_check in order to get a raw lock
3421 // without interfering with the safepoint mechanism. The routines are not JVM_LEAF because
3422 // they might be called by non-java threads. The JVM_LEAF installs a NoHandleMark check
3423 // that only works with java threads.
3424 
3425 
3426 JNIEXPORT void* JNICALL JVM_RawMonitorCreate(void) {
3427   VM_Exit::block_if_vm_exited();
3428   JVMWrapper("JVM_RawMonitorCreate");
3429   return new Mutex(Mutex::native, "JVM_RawMonitorCreate");
3430 }
3431 
3432 
3433 JNIEXPORT void JNICALL  JVM_RawMonitorDestroy(void *mon) {
3434   VM_Exit::block_if_vm_exited();
3435   JVMWrapper("JVM_RawMonitorDestroy");
3436   delete ((Mutex*) mon);
3437 }
3438 
3439 
3440 JNIEXPORT jint JNICALL JVM_RawMonitorEnter(void *mon) {
3441   VM_Exit::block_if_vm_exited();
3442   JVMWrapper("JVM_RawMonitorEnter");
3443   ((Mutex*) mon)->jvm_raw_lock();
3444   return 0;
3445 }
3446 
3447 
3448 JNIEXPORT void JNICALL JVM_RawMonitorExit(void *mon) {
3449   VM_Exit::block_if_vm_exited();
3450   JVMWrapper("JVM_RawMonitorExit");
3451   ((Mutex*) mon)->jvm_raw_unlock();
3452 }
3453 
3454 
3455 // Shared JNI/JVM entry points //////////////////////////////////////////////////////////////
3456 
3457 jclass find_class_from_class_loader(JNIEnv* env, Symbol* name, jboolean init,
3458                                     Handle loader, Handle protection_domain,
3459                                     jboolean throwError, TRAPS) {
3460   // Security Note:
3461   //   The Java level wrapper will perform the necessary security check allowing
3462   //   us to pass the NULL as the initiating class loader.  The VM is responsible for
3463   //   the checkPackageAccess relative to the initiating class loader via the
3464   //   protection_domain. The protection_domain is passed as NULL by the java code
3465   //   if there is no security manager in 3-arg Class.forName().
3466   Klass* klass = SystemDictionary::resolve_or_fail(name, loader, protection_domain, throwError != 0, CHECK_NULL);
3467 
3468   // Check if we should initialize the class
3469   if (init && klass->is_instance_klass()) {
3470     klass->initialize(CHECK_NULL);
3471   }
3472   return (jclass) JNIHandles::make_local(env, klass->java_mirror());
3473 }
3474 
3475 
3476 // Method ///////////////////////////////////////////////////////////////////////////////////////////
3477 
3478 JVM_ENTRY(jobject, JVM_InvokeMethod(JNIEnv *env, jobject method, jobject obj, jobjectArray args0))
3479   JVMWrapper("JVM_InvokeMethod");
3480   Handle method_handle;
3481   if (thread->stack_available((address) &method_handle) >= JVMInvokeMethodSlack) {
3482     method_handle = Handle(THREAD, JNIHandles::resolve(method));
3483     Handle receiver(THREAD, JNIHandles::resolve(obj));
3484     objArrayHandle args(THREAD, objArrayOop(JNIHandles::resolve(args0)));
3485     oop result = Reflection::invoke_method(method_handle(), receiver, args, CHECK_NULL);
3486     jobject res = JNIHandles::make_local(env, result);
3487     if (JvmtiExport::should_post_vm_object_alloc()) {
3488       oop ret_type = java_lang_reflect_Method::return_type(method_handle());
3489       assert(ret_type != NULL, "sanity check: ret_type oop must not be NULL!");
3490       if (java_lang_Class::is_primitive(ret_type)) {
3491         // Only for primitive type vm allocates memory for java object.
3492         // See box() method.
3493         JvmtiExport::post_vm_object_alloc(JavaThread::current(), result);
3494       }
3495     }
3496     return res;
3497   } else {
3498     THROW_0(vmSymbols::java_lang_StackOverflowError());
3499   }
3500 JVM_END
3501 
3502 
3503 JVM_ENTRY(jobject, JVM_NewInstanceFromConstructor(JNIEnv *env, jobject c, jobjectArray args0))
3504   JVMWrapper("JVM_NewInstanceFromConstructor");
3505   oop constructor_mirror = JNIHandles::resolve(c);
3506   objArrayHandle args(THREAD, objArrayOop(JNIHandles::resolve(args0)));
3507   oop result = Reflection::invoke_constructor(constructor_mirror, args, CHECK_NULL);
3508   jobject res = JNIHandles::make_local(env, result);
3509   if (JvmtiExport::should_post_vm_object_alloc()) {
3510     JvmtiExport::post_vm_object_alloc(JavaThread::current(), result);
3511   }
3512   return res;
3513 JVM_END
3514 
3515 // Atomic ///////////////////////////////////////////////////////////////////////////////////////////
3516 
3517 JVM_LEAF(jboolean, JVM_SupportsCX8())
3518   JVMWrapper("JVM_SupportsCX8");
3519   return VM_Version::supports_cx8();
3520 JVM_END
3521 
3522 JVM_ENTRY(void, JVM_InitializeFromArchive(JNIEnv* env, jclass cls))
3523   JVMWrapper("JVM_InitializeFromArchive");
3524   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve(cls));
3525   assert(k->is_klass(), "just checking");
3526   HeapShared::initialize_from_archived_subgraph(k);
3527 JVM_END
3528 
3529 // Returns an array of all live Thread objects (VM internal JavaThreads,
3530 // jvmti agent threads, and JNI attaching threads  are skipped)
3531 // See CR 6404306 regarding JNI attaching threads
3532 JVM_ENTRY(jobjectArray, JVM_GetAllThreads(JNIEnv *env, jclass dummy))
3533   ResourceMark rm(THREAD);
3534   ThreadsListEnumerator tle(THREAD, false, false);
3535   JvmtiVMObjectAllocEventCollector oam;
3536 
3537   int num_threads = tle.num_threads();
3538   objArrayOop r = oopFactory::new_objArray(SystemDictionary::Thread_klass(), num_threads, CHECK_NULL);
3539   objArrayHandle threads_ah(THREAD, r);
3540 
3541   for (int i = 0; i < num_threads; i++) {
3542     Handle h = tle.get_threadObj(i);
3543     threads_ah->obj_at_put(i, h());
3544   }
3545 
3546   return (jobjectArray) JNIHandles::make_local(env, threads_ah());
3547 JVM_END
3548 
3549 
3550 // Support for java.lang.Thread.getStackTrace() and getAllStackTraces() methods
3551 // Return StackTraceElement[][], each element is the stack trace of a thread in
3552 // the corresponding entry in the given threads array
3553 JVM_ENTRY(jobjectArray, JVM_DumpThreads(JNIEnv *env, jclass threadClass, jobjectArray threads))
3554   JVMWrapper("JVM_DumpThreads");
3555   JvmtiVMObjectAllocEventCollector oam;
3556 
3557   // Check if threads is null
3558   if (threads == NULL) {
3559     THROW_(vmSymbols::java_lang_NullPointerException(), 0);
3560   }
3561 
3562   objArrayOop a = objArrayOop(JNIHandles::resolve_non_null(threads));
3563   objArrayHandle ah(THREAD, a);
3564   int num_threads = ah->length();
3565   // check if threads is non-empty array
3566   if (num_threads == 0) {
3567     THROW_(vmSymbols::java_lang_IllegalArgumentException(), 0);
3568   }
3569 
3570   // check if threads is not an array of objects of Thread class
3571   Klass* k = ObjArrayKlass::cast(ah->klass())->element_klass();
3572   if (k != SystemDictionary::Thread_klass()) {
3573     THROW_(vmSymbols::java_lang_IllegalArgumentException(), 0);
3574   }
3575 
3576   ResourceMark rm(THREAD);
3577 
3578   GrowableArray<instanceHandle>* thread_handle_array = new GrowableArray<instanceHandle>(num_threads);
3579   for (int i = 0; i < num_threads; i++) {
3580     oop thread_obj = ah->obj_at(i);
3581     instanceHandle h(THREAD, (instanceOop) thread_obj);
3582     thread_handle_array->append(h);
3583   }
3584 
3585   // The JavaThread references in thread_handle_array are validated
3586   // in VM_ThreadDump::doit().
3587   Handle stacktraces = ThreadService::dump_stack_traces(thread_handle_array, num_threads, CHECK_NULL);
3588   return (jobjectArray)JNIHandles::make_local(env, stacktraces());
3589 
3590 JVM_END
3591 
3592 // JVM monitoring and management support
3593 JVM_ENTRY_NO_ENV(void*, JVM_GetManagement(jint version))
3594   return Management::get_jmm_interface(version);
3595 JVM_END
3596 
3597 // com.sun.tools.attach.VirtualMachine agent properties support
3598 //
3599 // Initialize the agent properties with the properties maintained in the VM
3600 JVM_ENTRY(jobject, JVM_InitAgentProperties(JNIEnv *env, jobject properties))
3601   JVMWrapper("JVM_InitAgentProperties");
3602   ResourceMark rm;
3603 
3604   Handle props(THREAD, JNIHandles::resolve_non_null(properties));
3605 
3606   PUTPROP(props, "sun.java.command", Arguments::java_command());
3607   PUTPROP(props, "sun.jvm.flags", Arguments::jvm_flags());
3608   PUTPROP(props, "sun.jvm.args", Arguments::jvm_args());
3609   return properties;
3610 JVM_END
3611 
3612 JVM_ENTRY(jobjectArray, JVM_GetEnclosingMethodInfo(JNIEnv *env, jclass ofClass))
3613 {
3614   JVMWrapper("JVM_GetEnclosingMethodInfo");
3615   JvmtiVMObjectAllocEventCollector oam;
3616 
3617   if (ofClass == NULL) {
3618     return NULL;
3619   }
3620   Handle mirror(THREAD, JNIHandles::resolve_non_null(ofClass));
3621   // Special handling for primitive objects
3622   if (java_lang_Class::is_primitive(mirror())) {
3623     return NULL;
3624   }
3625   Klass* k = java_lang_Class::as_Klass(mirror());
3626   if (!k->is_instance_klass()) {
3627     return NULL;
3628   }
3629   InstanceKlass* ik = InstanceKlass::cast(k);
3630   int encl_method_class_idx = ik->enclosing_method_class_index();
3631   if (encl_method_class_idx == 0) {
3632     return NULL;
3633   }
3634   objArrayOop dest_o = oopFactory::new_objArray(SystemDictionary::Object_klass(), 3, CHECK_NULL);
3635   objArrayHandle dest(THREAD, dest_o);
3636   Klass* enc_k = ik->constants()->klass_at(encl_method_class_idx, CHECK_NULL);
3637   dest->obj_at_put(0, enc_k->java_mirror());
3638   int encl_method_method_idx = ik->enclosing_method_method_index();
3639   if (encl_method_method_idx != 0) {
3640     Symbol* sym = ik->constants()->symbol_at(
3641                         extract_low_short_from_int(
3642                           ik->constants()->name_and_type_at(encl_method_method_idx)));
3643     Handle str = java_lang_String::create_from_symbol(sym, CHECK_NULL);
3644     dest->obj_at_put(1, str());
3645     sym = ik->constants()->symbol_at(
3646               extract_high_short_from_int(
3647                 ik->constants()->name_and_type_at(encl_method_method_idx)));
3648     str = java_lang_String::create_from_symbol(sym, CHECK_NULL);
3649     dest->obj_at_put(2, str());
3650   }
3651   return (jobjectArray) JNIHandles::make_local(dest());
3652 }
3653 JVM_END
3654 
3655 JVM_ENTRY(void, JVM_GetVersionInfo(JNIEnv* env, jvm_version_info* info, size_t info_size))
3656 {
3657   memset(info, 0, info_size);
3658 
3659   info->jvm_version = VM_Version::jvm_version();
3660   info->patch_version = VM_Version::vm_patch_version();
3661 
3662   // when we add a new capability in the jvm_version_info struct, we should also
3663   // consider to expose this new capability in the sun.rt.jvmCapabilities jvmstat
3664   // counter defined in runtimeService.cpp.
3665   info->is_attach_supported = AttachListener::is_attach_supported();
3666 }
3667 JVM_END
3668 
3669 // Returns an array of java.lang.String objects containing the input arguments to the VM.
3670 JVM_ENTRY(jobjectArray, JVM_GetVmArguments(JNIEnv *env))
3671   ResourceMark rm(THREAD);
3672 
3673   if (Arguments::num_jvm_args() == 0 && Arguments::num_jvm_flags() == 0) {
3674     return NULL;
3675   }
3676 
3677   char** vm_flags = Arguments::jvm_flags_array();
3678   char** vm_args = Arguments::jvm_args_array();
3679   int num_flags = Arguments::num_jvm_flags();
3680   int num_args = Arguments::num_jvm_args();
3681 
3682   InstanceKlass* ik = SystemDictionary::String_klass();
3683   objArrayOop r = oopFactory::new_objArray(ik, num_args + num_flags, CHECK_NULL);
3684   objArrayHandle result_h(THREAD, r);
3685 
3686   int index = 0;
3687   for (int j = 0; j < num_flags; j++, index++) {
3688     Handle h = java_lang_String::create_from_platform_dependent_str(vm_flags[j], CHECK_NULL);
3689     result_h->obj_at_put(index, h());
3690   }
3691   for (int i = 0; i < num_args; i++, index++) {
3692     Handle h = java_lang_String::create_from_platform_dependent_str(vm_args[i], CHECK_NULL);
3693     result_h->obj_at_put(index, h());
3694   }
3695   return (jobjectArray) JNIHandles::make_local(env, result_h());
3696 JVM_END
3697 
3698 JVM_ENTRY_NO_ENV(jint, JVM_FindSignal(const char *name))
3699   return os::get_signal_number(name);
3700 JVM_END