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