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