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