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