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   return ArrayKlass::cast(k)->element_access_is_atomic();
2336 JVM_END
2337 
2338 JVM_ENTRY(jobject, JVM_ArrayEnsureAccessAtomic(JNIEnv *env, jclass unused, jobject array))
2339   JVMWrapper("JVM_ArrayEnsureAccessAtomic");
2340   oop o = JNIHandles::resolve(array);
2341   Klass* k = o->klass();
2342   if ((o == NULL) || (!k->is_array_klass())) {
2343     THROW_0(vmSymbols::java_lang_IllegalArgumentException());
2344   }
2345   if (k->is_valueArray_klass()) {
2346     ValueArrayKlass* vk = ValueArrayKlass::cast(k);
2347     if (!vk->element_access_is_atomic()) {
2348       /**
2349        * Need to decide how to implement:
2350        *
2351        * 1) Change to objArrayOop layout, therefore oop->klass() differs so
2352        * then "<atomic>[Qfoo;" klass needs to subclass "[Qfoo;" to pass through
2353        * "checkcast" & "instanceof"
2354        *
2355        * 2) Use extra header in the valueArrayOop to flag atomicity required and
2356        * possibly per instance lock structure. Said info, could be placed in
2357        * "trailer" rather than disturb the current arrayOop
2358        */
2359       Unimplemented();
2360     }
2361   }
2362   return array;
2363 JVM_END
2364 
2365 // Verification ////////////////////////////////////////////////////////////////////////////////
2366 
2367 // Reflection for the verifier /////////////////////////////////////////////////////////////////
2368 
2369 // RedefineClasses support: bug 6214132 caused verification to fail.
2370 // All functions from this section should call the jvmtiThreadSate function:
2371 //   Klass* class_to_verify_considering_redefinition(Klass* klass).
2372 // The function returns a Klass* of the _scratch_class if the verifier
2373 // was invoked in the middle of the class redefinition.
2374 // Otherwise it returns its argument value which is the _the_class Klass*.
2375 // Please, refer to the description in the jvmtiThreadSate.hpp.
2376 
2377 JVM_ENTRY(const char*, JVM_GetClassNameUTF(JNIEnv *env, jclass cls))
2378   JVMWrapper("JVM_GetClassNameUTF");
2379   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2380   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2381   return k->name()->as_utf8();
2382 JVM_END
2383 
2384 
2385 JVM_ENTRY(void, JVM_GetClassCPTypes(JNIEnv *env, jclass cls, unsigned char *types))
2386   JVMWrapper("JVM_GetClassCPTypes");
2387   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2388   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2389   // types will have length zero if this is not an InstanceKlass
2390   // (length is determined by call to JVM_GetClassCPEntriesCount)
2391   if (k->is_instance_klass()) {
2392     ConstantPool* cp = InstanceKlass::cast(k)->constants();
2393     for (int index = cp->length() - 1; index >= 0; index--) {
2394       constantTag tag = cp->tag_at(index);
2395       types[index] = (tag.is_unresolved_klass()) ? (unsigned char) JVM_CONSTANT_Class : tag.value();
2396     }
2397   }
2398 JVM_END
2399 
2400 
2401 JVM_ENTRY(jint, JVM_GetClassCPEntriesCount(JNIEnv *env, jclass cls))
2402   JVMWrapper("JVM_GetClassCPEntriesCount");
2403   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2404   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2405   return (!k->is_instance_klass()) ? 0 : InstanceKlass::cast(k)->constants()->length();
2406 JVM_END
2407 
2408 
2409 JVM_ENTRY(jint, JVM_GetClassFieldsCount(JNIEnv *env, jclass cls))
2410   JVMWrapper("JVM_GetClassFieldsCount");
2411   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2412   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2413   return (!k->is_instance_klass()) ? 0 : InstanceKlass::cast(k)->java_fields_count();
2414 JVM_END
2415 
2416 
2417 JVM_ENTRY(jint, JVM_GetClassMethodsCount(JNIEnv *env, jclass cls))
2418   JVMWrapper("JVM_GetClassMethodsCount");
2419   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2420   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2421   return (!k->is_instance_klass()) ? 0 : InstanceKlass::cast(k)->methods()->length();
2422 JVM_END
2423 
2424 
2425 // The following methods, used for the verifier, are never called with
2426 // array klasses, so a direct cast to InstanceKlass is safe.
2427 // Typically, these methods are called in a loop with bounds determined
2428 // by the results of JVM_GetClass{Fields,Methods}Count, which return
2429 // zero for arrays.
2430 JVM_ENTRY(void, JVM_GetMethodIxExceptionIndexes(JNIEnv *env, jclass cls, jint method_index, unsigned short *exceptions))
2431   JVMWrapper("JVM_GetMethodIxExceptionIndexes");
2432   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2433   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2434   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2435   int length = method->checked_exceptions_length();
2436   if (length > 0) {
2437     CheckedExceptionElement* table= method->checked_exceptions_start();
2438     for (int i = 0; i < length; i++) {
2439       exceptions[i] = table[i].class_cp_index;
2440     }
2441   }
2442 JVM_END
2443 
2444 
2445 JVM_ENTRY(jint, JVM_GetMethodIxExceptionsCount(JNIEnv *env, jclass cls, jint method_index))
2446   JVMWrapper("JVM_GetMethodIxExceptionsCount");
2447   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2448   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2449   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2450   return method->checked_exceptions_length();
2451 JVM_END
2452 
2453 
2454 JVM_ENTRY(void, JVM_GetMethodIxByteCode(JNIEnv *env, jclass cls, jint method_index, unsigned char *code))
2455   JVMWrapper("JVM_GetMethodIxByteCode");
2456   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2457   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2458   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2459   memcpy(code, method->code_base(), method->code_size());
2460 JVM_END
2461 
2462 
2463 JVM_ENTRY(jint, JVM_GetMethodIxByteCodeLength(JNIEnv *env, jclass cls, jint method_index))
2464   JVMWrapper("JVM_GetMethodIxByteCodeLength");
2465   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2466   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2467   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2468   return method->code_size();
2469 JVM_END
2470 
2471 
2472 JVM_ENTRY(void, JVM_GetMethodIxExceptionTableEntry(JNIEnv *env, jclass cls, jint method_index, jint entry_index, JVM_ExceptionTableEntryType *entry))
2473   JVMWrapper("JVM_GetMethodIxExceptionTableEntry");
2474   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2475   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2476   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2477   ExceptionTable extable(method);
2478   entry->start_pc   = extable.start_pc(entry_index);
2479   entry->end_pc     = extable.end_pc(entry_index);
2480   entry->handler_pc = extable.handler_pc(entry_index);
2481   entry->catchType  = extable.catch_type_index(entry_index);
2482 JVM_END
2483 
2484 
2485 JVM_ENTRY(jint, JVM_GetMethodIxExceptionTableLength(JNIEnv *env, jclass cls, int method_index))
2486   JVMWrapper("JVM_GetMethodIxExceptionTableLength");
2487   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2488   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2489   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2490   return method->exception_table_length();
2491 JVM_END
2492 
2493 
2494 JVM_ENTRY(jint, JVM_GetMethodIxModifiers(JNIEnv *env, jclass cls, int method_index))
2495   JVMWrapper("JVM_GetMethodIxModifiers");
2496   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2497   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2498   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2499   return method->access_flags().as_int() & JVM_RECOGNIZED_METHOD_MODIFIERS;
2500 JVM_END
2501 
2502 
2503 JVM_ENTRY(jint, JVM_GetFieldIxModifiers(JNIEnv *env, jclass cls, int field_index))
2504   JVMWrapper("JVM_GetFieldIxModifiers");
2505   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2506   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2507   return InstanceKlass::cast(k)->field_access_flags(field_index) & JVM_RECOGNIZED_FIELD_MODIFIERS;
2508 JVM_END
2509 
2510 
2511 JVM_ENTRY(jint, JVM_GetMethodIxLocalsCount(JNIEnv *env, jclass cls, int method_index))
2512   JVMWrapper("JVM_GetMethodIxLocalsCount");
2513   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2514   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2515   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2516   return method->max_locals();
2517 JVM_END
2518 
2519 
2520 JVM_ENTRY(jint, JVM_GetMethodIxArgsSize(JNIEnv *env, jclass cls, int method_index))
2521   JVMWrapper("JVM_GetMethodIxArgsSize");
2522   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2523   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2524   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2525   return method->size_of_parameters();
2526 JVM_END
2527 
2528 
2529 JVM_ENTRY(jint, JVM_GetMethodIxMaxStack(JNIEnv *env, jclass cls, int method_index))
2530   JVMWrapper("JVM_GetMethodIxMaxStack");
2531   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2532   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2533   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2534   return method->verifier_max_stack();
2535 JVM_END
2536 
2537 
2538 JVM_ENTRY(jboolean, JVM_IsConstructorIx(JNIEnv *env, jclass cls, int method_index))
2539   JVMWrapper("JVM_IsConstructorIx");
2540   ResourceMark rm(THREAD);
2541   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2542   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2543   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2544   return method->is_object_constructor();
2545 JVM_END
2546 
2547 
2548 JVM_ENTRY(jboolean, JVM_IsVMGeneratedMethodIx(JNIEnv *env, jclass cls, int method_index))
2549   JVMWrapper("JVM_IsVMGeneratedMethodIx");
2550   ResourceMark rm(THREAD);
2551   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2552   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2553   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2554   return method->is_overpass();
2555 JVM_END
2556 
2557 JVM_ENTRY(const char*, JVM_GetMethodIxNameUTF(JNIEnv *env, jclass cls, jint method_index))
2558   JVMWrapper("JVM_GetMethodIxIxUTF");
2559   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2560   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2561   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2562   return method->name()->as_utf8();
2563 JVM_END
2564 
2565 
2566 JVM_ENTRY(const char*, JVM_GetMethodIxSignatureUTF(JNIEnv *env, jclass cls, jint method_index))
2567   JVMWrapper("JVM_GetMethodIxSignatureUTF");
2568   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2569   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2570   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2571   return method->signature()->as_utf8();
2572 JVM_END
2573 
2574 /**
2575  * All of these JVM_GetCP-xxx methods are used by the old verifier to
2576  * read entries in the constant pool.  Since the old verifier always
2577  * works on a copy of the code, it will not see any rewriting that
2578  * may possibly occur in the middle of verification.  So it is important
2579  * that nothing it calls tries to use the cpCache instead of the raw
2580  * constant pool, so we must use cp->uncached_x methods when appropriate.
2581  */
2582 JVM_ENTRY(const char*, JVM_GetCPFieldNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2583   JVMWrapper("JVM_GetCPFieldNameUTF");
2584   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2585   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2586   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2587   switch (cp->tag_at(cp_index).value()) {
2588     case JVM_CONSTANT_Fieldref:
2589       return cp->uncached_name_ref_at(cp_index)->as_utf8();
2590     default:
2591       fatal("JVM_GetCPFieldNameUTF: illegal constant");
2592   }
2593   ShouldNotReachHere();
2594   return NULL;
2595 JVM_END
2596 
2597 
2598 JVM_ENTRY(const char*, JVM_GetCPMethodNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2599   JVMWrapper("JVM_GetCPMethodNameUTF");
2600   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2601   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2602   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2603   switch (cp->tag_at(cp_index).value()) {
2604     case JVM_CONSTANT_InterfaceMethodref:
2605     case JVM_CONSTANT_Methodref:
2606       return cp->uncached_name_ref_at(cp_index)->as_utf8();
2607     default:
2608       fatal("JVM_GetCPMethodNameUTF: illegal constant");
2609   }
2610   ShouldNotReachHere();
2611   return NULL;
2612 JVM_END
2613 
2614 
2615 JVM_ENTRY(const char*, JVM_GetCPMethodSignatureUTF(JNIEnv *env, jclass cls, jint cp_index))
2616   JVMWrapper("JVM_GetCPMethodSignatureUTF");
2617   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2618   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2619   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2620   switch (cp->tag_at(cp_index).value()) {
2621     case JVM_CONSTANT_InterfaceMethodref:
2622     case JVM_CONSTANT_Methodref:
2623       return cp->uncached_signature_ref_at(cp_index)->as_utf8();
2624     default:
2625       fatal("JVM_GetCPMethodSignatureUTF: illegal constant");
2626   }
2627   ShouldNotReachHere();
2628   return NULL;
2629 JVM_END
2630 
2631 
2632 JVM_ENTRY(const char*, JVM_GetCPFieldSignatureUTF(JNIEnv *env, jclass cls, jint cp_index))
2633   JVMWrapper("JVM_GetCPFieldSignatureUTF");
2634   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2635   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2636   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2637   switch (cp->tag_at(cp_index).value()) {
2638     case JVM_CONSTANT_Fieldref:
2639       return cp->uncached_signature_ref_at(cp_index)->as_utf8();
2640     default:
2641       fatal("JVM_GetCPFieldSignatureUTF: illegal constant");
2642   }
2643   ShouldNotReachHere();
2644   return NULL;
2645 JVM_END
2646 
2647 
2648 JVM_ENTRY(const char*, JVM_GetCPClassNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2649   JVMWrapper("JVM_GetCPClassNameUTF");
2650   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2651   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2652   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2653   Symbol* classname = cp->klass_name_at(cp_index);
2654   return classname->as_utf8();
2655 JVM_END
2656 
2657 
2658 JVM_ENTRY(const char*, JVM_GetCPFieldClassNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2659   JVMWrapper("JVM_GetCPFieldClassNameUTF");
2660   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2661   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2662   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2663   switch (cp->tag_at(cp_index).value()) {
2664     case JVM_CONSTANT_Fieldref: {
2665       int class_index = cp->uncached_klass_ref_index_at(cp_index);
2666       Symbol* classname = cp->klass_name_at(class_index);
2667       return classname->as_utf8();
2668     }
2669     default:
2670       fatal("JVM_GetCPFieldClassNameUTF: illegal constant");
2671   }
2672   ShouldNotReachHere();
2673   return NULL;
2674 JVM_END
2675 
2676 
2677 JVM_ENTRY(const char*, JVM_GetCPMethodClassNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2678   JVMWrapper("JVM_GetCPMethodClassNameUTF");
2679   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2680   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2681   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2682   switch (cp->tag_at(cp_index).value()) {
2683     case JVM_CONSTANT_Methodref:
2684     case JVM_CONSTANT_InterfaceMethodref: {
2685       int class_index = cp->uncached_klass_ref_index_at(cp_index);
2686       Symbol* classname = cp->klass_name_at(class_index);
2687       return classname->as_utf8();
2688     }
2689     default:
2690       fatal("JVM_GetCPMethodClassNameUTF: illegal constant");
2691   }
2692   ShouldNotReachHere();
2693   return NULL;
2694 JVM_END
2695 
2696 
2697 JVM_ENTRY(jint, JVM_GetCPFieldModifiers(JNIEnv *env, jclass cls, int cp_index, jclass called_cls))
2698   JVMWrapper("JVM_GetCPFieldModifiers");
2699   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2700   Klass* k_called = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(called_cls));
2701   k        = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2702   k_called = JvmtiThreadState::class_to_verify_considering_redefinition(k_called, thread);
2703   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2704   ConstantPool* cp_called = InstanceKlass::cast(k_called)->constants();
2705   switch (cp->tag_at(cp_index).value()) {
2706     case JVM_CONSTANT_Fieldref: {
2707       Symbol* name      = cp->uncached_name_ref_at(cp_index);
2708       Symbol* signature = cp->uncached_signature_ref_at(cp_index);
2709       InstanceKlass* ik = InstanceKlass::cast(k_called);
2710       for (JavaFieldStream fs(ik); !fs.done(); fs.next()) {
2711         if (fs.name() == name && fs.signature() == signature) {
2712           return fs.access_flags().as_short() & JVM_RECOGNIZED_FIELD_MODIFIERS;
2713         }
2714       }
2715       return -1;
2716     }
2717     default:
2718       fatal("JVM_GetCPFieldModifiers: illegal constant");
2719   }
2720   ShouldNotReachHere();
2721   return 0;
2722 JVM_END
2723 
2724 
2725 JVM_ENTRY(jint, JVM_GetCPMethodModifiers(JNIEnv *env, jclass cls, int cp_index, jclass called_cls))
2726   JVMWrapper("JVM_GetCPMethodModifiers");
2727   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2728   Klass* k_called = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(called_cls));
2729   k        = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2730   k_called = JvmtiThreadState::class_to_verify_considering_redefinition(k_called, thread);
2731   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2732   switch (cp->tag_at(cp_index).value()) {
2733     case JVM_CONSTANT_Methodref:
2734     case JVM_CONSTANT_InterfaceMethodref: {
2735       Symbol* name      = cp->uncached_name_ref_at(cp_index);
2736       Symbol* signature = cp->uncached_signature_ref_at(cp_index);
2737       Array<Method*>* methods = InstanceKlass::cast(k_called)->methods();
2738       int methods_count = methods->length();
2739       for (int i = 0; i < methods_count; i++) {
2740         Method* method = methods->at(i);
2741         if (method->name() == name && method->signature() == signature) {
2742             return method->access_flags().as_int() & JVM_RECOGNIZED_METHOD_MODIFIERS;
2743         }
2744       }
2745       return -1;
2746     }
2747     default:
2748       fatal("JVM_GetCPMethodModifiers: illegal constant");
2749   }
2750   ShouldNotReachHere();
2751   return 0;
2752 JVM_END
2753 
2754 
2755 // Misc //////////////////////////////////////////////////////////////////////////////////////////////
2756 
2757 JVM_LEAF(void, JVM_ReleaseUTF(const char *utf))
2758   // So long as UTF8::convert_to_utf8 returns resource strings, we don't have to do anything
2759 JVM_END
2760 
2761 
2762 JVM_ENTRY(jboolean, JVM_IsSameClassPackage(JNIEnv *env, jclass class1, jclass class2))
2763   JVMWrapper("JVM_IsSameClassPackage");
2764   oop class1_mirror = JNIHandles::resolve_non_null(class1);
2765   oop class2_mirror = JNIHandles::resolve_non_null(class2);
2766   Klass* klass1 = java_lang_Class::as_Klass(class1_mirror);
2767   Klass* klass2 = java_lang_Class::as_Klass(class2_mirror);
2768   return (jboolean) Reflection::is_same_class_package(klass1, klass2);
2769 JVM_END
2770 
2771 // Printing support //////////////////////////////////////////////////
2772 extern "C" {
2773 
2774 ATTRIBUTE_PRINTF(3, 0)
2775 int jio_vsnprintf(char *str, size_t count, const char *fmt, va_list args) {
2776   // Reject count values that are negative signed values converted to
2777   // unsigned; see bug 4399518, 4417214
2778   if ((intptr_t)count <= 0) return -1;
2779 
2780   int result = os::vsnprintf(str, count, fmt, args);
2781   if (result > 0 && (size_t)result >= count) {
2782     result = -1;
2783   }
2784 
2785   return result;
2786 }
2787 
2788 ATTRIBUTE_PRINTF(3, 4)
2789 int jio_snprintf(char *str, size_t count, const char *fmt, ...) {
2790   va_list args;
2791   int len;
2792   va_start(args, fmt);
2793   len = jio_vsnprintf(str, count, fmt, args);
2794   va_end(args);
2795   return len;
2796 }
2797 
2798 ATTRIBUTE_PRINTF(2, 3)
2799 int jio_fprintf(FILE* f, const char *fmt, ...) {
2800   int len;
2801   va_list args;
2802   va_start(args, fmt);
2803   len = jio_vfprintf(f, fmt, args);
2804   va_end(args);
2805   return len;
2806 }
2807 
2808 ATTRIBUTE_PRINTF(2, 0)
2809 int jio_vfprintf(FILE* f, const char *fmt, va_list args) {
2810   if (Arguments::vfprintf_hook() != NULL) {
2811      return Arguments::vfprintf_hook()(f, fmt, args);
2812   } else {
2813     return vfprintf(f, fmt, args);
2814   }
2815 }
2816 
2817 ATTRIBUTE_PRINTF(1, 2)
2818 JNIEXPORT int jio_printf(const char *fmt, ...) {
2819   int len;
2820   va_list args;
2821   va_start(args, fmt);
2822   len = jio_vfprintf(defaultStream::output_stream(), fmt, args);
2823   va_end(args);
2824   return len;
2825 }
2826 
2827 // HotSpot specific jio method
2828 void jio_print(const char* s, size_t len) {
2829   // Try to make this function as atomic as possible.
2830   if (Arguments::vfprintf_hook() != NULL) {
2831     jio_fprintf(defaultStream::output_stream(), "%.*s", (int)len, s);
2832   } else {
2833     // Make an unused local variable to avoid warning from gcc compiler.
2834     size_t count = ::write(defaultStream::output_fd(), s, (int)len);
2835   }
2836 }
2837 
2838 } // Extern C
2839 
2840 // java.lang.Thread //////////////////////////////////////////////////////////////////////////////
2841 
2842 // In most of the JVM thread support functions we need to access the
2843 // thread through a ThreadsListHandle to prevent it from exiting and
2844 // being reclaimed while we try to operate on it. The exceptions to this
2845 // rule are when operating on the current thread, or if the monitor of
2846 // the target java.lang.Thread is locked at the Java level - in both
2847 // cases the target cannot exit.
2848 
2849 static void thread_entry(JavaThread* thread, TRAPS) {
2850   HandleMark hm(THREAD);
2851   Handle obj(THREAD, thread->threadObj());
2852   JavaValue result(T_VOID);
2853   JavaCalls::call_virtual(&result,
2854                           obj,
2855                           SystemDictionary::Thread_klass(),
2856                           vmSymbols::run_method_name(),
2857                           vmSymbols::void_method_signature(),
2858                           THREAD);
2859 }
2860 
2861 
2862 JVM_ENTRY(void, JVM_StartThread(JNIEnv* env, jobject jthread))
2863   JVMWrapper("JVM_StartThread");
2864   JavaThread *native_thread = NULL;
2865 
2866   // We cannot hold the Threads_lock when we throw an exception,
2867   // due to rank ordering issues. Example:  we might need to grab the
2868   // Heap_lock while we construct the exception.
2869   bool throw_illegal_thread_state = false;
2870 
2871   // We must release the Threads_lock before we can post a jvmti event
2872   // in Thread::start.
2873   {
2874     // Ensure that the C++ Thread and OSThread structures aren't freed before
2875     // we operate.
2876     MutexLocker mu(Threads_lock);
2877 
2878     // Since JDK 5 the java.lang.Thread threadStatus is used to prevent
2879     // re-starting an already started thread, so we should usually find
2880     // that the JavaThread is null. However for a JNI attached thread
2881     // there is a small window between the Thread object being created
2882     // (with its JavaThread set) and the update to its threadStatus, so we
2883     // have to check for this
2884     if (java_lang_Thread::thread(JNIHandles::resolve_non_null(jthread)) != NULL) {
2885       throw_illegal_thread_state = true;
2886     } else {
2887       // We could also check the stillborn flag to see if this thread was already stopped, but
2888       // for historical reasons we let the thread detect that itself when it starts running
2889 
2890       jlong size =
2891              java_lang_Thread::stackSize(JNIHandles::resolve_non_null(jthread));
2892       // Allocate the C++ Thread structure and create the native thread.  The
2893       // stack size retrieved from java is 64-bit signed, but the constructor takes
2894       // size_t (an unsigned type), which may be 32 or 64-bit depending on the platform.
2895       //  - Avoid truncating on 32-bit platforms if size is greater than UINT_MAX.
2896       //  - Avoid passing negative values which would result in really large stacks.
2897       NOT_LP64(if (size > SIZE_MAX) size = SIZE_MAX;)
2898       size_t sz = size > 0 ? (size_t) size : 0;
2899       native_thread = new JavaThread(&thread_entry, sz);
2900 
2901       // At this point it may be possible that no osthread was created for the
2902       // JavaThread due to lack of memory. Check for this situation and throw
2903       // an exception if necessary. Eventually we may want to change this so
2904       // that we only grab the lock if the thread was created successfully -
2905       // then we can also do this check and throw the exception in the
2906       // JavaThread constructor.
2907       if (native_thread->osthread() != NULL) {
2908         // Note: the current thread is not being used within "prepare".
2909         native_thread->prepare(jthread);
2910       }
2911     }
2912   }
2913 
2914   if (throw_illegal_thread_state) {
2915     THROW(vmSymbols::java_lang_IllegalThreadStateException());
2916   }
2917 
2918   assert(native_thread != NULL, "Starting null thread?");
2919 
2920   if (native_thread->osthread() == NULL) {
2921     // No one should hold a reference to the 'native_thread'.
2922     native_thread->smr_delete();
2923     if (JvmtiExport::should_post_resource_exhausted()) {
2924       JvmtiExport::post_resource_exhausted(
2925         JVMTI_RESOURCE_EXHAUSTED_OOM_ERROR | JVMTI_RESOURCE_EXHAUSTED_THREADS,
2926         os::native_thread_creation_failed_msg());
2927     }
2928     THROW_MSG(vmSymbols::java_lang_OutOfMemoryError(),
2929               os::native_thread_creation_failed_msg());
2930   }
2931 
2932   Thread::start(native_thread);
2933 
2934 JVM_END
2935 
2936 
2937 // JVM_Stop is implemented using a VM_Operation, so threads are forced to safepoints
2938 // before the quasi-asynchronous exception is delivered.  This is a little obtrusive,
2939 // but is thought to be reliable and simple. In the case, where the receiver is the
2940 // same thread as the sender, no VM_Operation is needed.
2941 JVM_ENTRY(void, JVM_StopThread(JNIEnv* env, jobject jthread, jobject throwable))
2942   JVMWrapper("JVM_StopThread");
2943 
2944   // A nested ThreadsListHandle will grab the Threads_lock so create
2945   // tlh before we resolve throwable.
2946   ThreadsListHandle tlh(thread);
2947   oop java_throwable = JNIHandles::resolve(throwable);
2948   if (java_throwable == NULL) {
2949     THROW(vmSymbols::java_lang_NullPointerException());
2950   }
2951   oop java_thread = NULL;
2952   JavaThread* receiver = NULL;
2953   bool is_alive = tlh.cv_internal_thread_to_JavaThread(jthread, &receiver, &java_thread);
2954   Events::log_exception(thread,
2955                         "JVM_StopThread thread JavaThread " INTPTR_FORMAT " as oop " INTPTR_FORMAT " [exception " INTPTR_FORMAT "]",
2956                         p2i(receiver), p2i(java_thread), p2i(throwable));
2957 
2958   if (is_alive) {
2959     // jthread refers to a live JavaThread.
2960     if (thread == receiver) {
2961       // Exception is getting thrown at self so no VM_Operation needed.
2962       THROW_OOP(java_throwable);
2963     } else {
2964       // Use a VM_Operation to throw the exception.
2965       Thread::send_async_exception(java_thread, java_throwable);
2966     }
2967   } else {
2968     // Either:
2969     // - target thread has not been started before being stopped, or
2970     // - target thread already terminated
2971     // We could read the threadStatus to determine which case it is
2972     // but that is overkill as it doesn't matter. We must set the
2973     // stillborn flag for the first case, and if the thread has already
2974     // exited setting this flag has no effect.
2975     java_lang_Thread::set_stillborn(java_thread);
2976   }
2977 JVM_END
2978 
2979 
2980 JVM_ENTRY(jboolean, JVM_IsThreadAlive(JNIEnv* env, jobject jthread))
2981   JVMWrapper("JVM_IsThreadAlive");
2982 
2983   oop thread_oop = JNIHandles::resolve_non_null(jthread);
2984   return java_lang_Thread::is_alive(thread_oop);
2985 JVM_END
2986 
2987 
2988 JVM_ENTRY(void, JVM_SuspendThread(JNIEnv* env, jobject jthread))
2989   JVMWrapper("JVM_SuspendThread");
2990 
2991   ThreadsListHandle tlh(thread);
2992   JavaThread* receiver = NULL;
2993   bool is_alive = tlh.cv_internal_thread_to_JavaThread(jthread, &receiver, NULL);
2994   if (is_alive) {
2995     // jthread refers to a live JavaThread.
2996     {
2997       MutexLocker ml(receiver->SR_lock(), Mutex::_no_safepoint_check_flag);
2998       if (receiver->is_external_suspend()) {
2999         // Don't allow nested external suspend requests. We can't return
3000         // an error from this interface so just ignore the problem.
3001         return;
3002       }
3003       if (receiver->is_exiting()) { // thread is in the process of exiting
3004         return;
3005       }
3006       receiver->set_external_suspend();
3007     }
3008 
3009     // java_suspend() will catch threads in the process of exiting
3010     // and will ignore them.
3011     receiver->java_suspend();
3012 
3013     // It would be nice to have the following assertion in all the
3014     // time, but it is possible for a racing resume request to have
3015     // resumed this thread right after we suspended it. Temporarily
3016     // enable this assertion if you are chasing a different kind of
3017     // bug.
3018     //
3019     // assert(java_lang_Thread::thread(receiver->threadObj()) == NULL ||
3020     //   receiver->is_being_ext_suspended(), "thread is not suspended");
3021   }
3022 JVM_END
3023 
3024 
3025 JVM_ENTRY(void, JVM_ResumeThread(JNIEnv* env, jobject jthread))
3026   JVMWrapper("JVM_ResumeThread");
3027 
3028   ThreadsListHandle tlh(thread);
3029   JavaThread* receiver = NULL;
3030   bool is_alive = tlh.cv_internal_thread_to_JavaThread(jthread, &receiver, NULL);
3031   if (is_alive) {
3032     // jthread refers to a live JavaThread.
3033 
3034     // This is the original comment for this Threads_lock grab:
3035     //   We need to *always* get the threads lock here, since this operation cannot be allowed during
3036     //   a safepoint. The safepoint code relies on suspending a thread to examine its state. If other
3037     //   threads randomly resumes threads, then a thread might not be suspended when the safepoint code
3038     //   looks at it.
3039     //
3040     // The above comment dates back to when we had both internal and
3041     // external suspend APIs that shared a common underlying mechanism.
3042     // External suspend is now entirely cooperative and doesn't share
3043     // anything with internal suspend. That said, there are some
3044     // assumptions in the VM that an external resume grabs the
3045     // Threads_lock. We can't drop the Threads_lock grab here until we
3046     // resolve the assumptions that exist elsewhere.
3047     //
3048     MutexLocker ml(Threads_lock);
3049     receiver->java_resume();
3050   }
3051 JVM_END
3052 
3053 
3054 JVM_ENTRY(void, JVM_SetThreadPriority(JNIEnv* env, jobject jthread, jint prio))
3055   JVMWrapper("JVM_SetThreadPriority");
3056 
3057   ThreadsListHandle tlh(thread);
3058   oop java_thread = NULL;
3059   JavaThread* receiver = NULL;
3060   bool is_alive = tlh.cv_internal_thread_to_JavaThread(jthread, &receiver, &java_thread);
3061   java_lang_Thread::set_priority(java_thread, (ThreadPriority)prio);
3062 
3063   if (is_alive) {
3064     // jthread refers to a live JavaThread.
3065     Thread::set_priority(receiver, (ThreadPriority)prio);
3066   }
3067   // Implied else: If the JavaThread hasn't started yet, then the
3068   // priority set in the java.lang.Thread object above will be pushed
3069   // down when it does start.
3070 JVM_END
3071 
3072 
3073 JVM_ENTRY(void, JVM_Yield(JNIEnv *env, jclass threadClass))
3074   JVMWrapper("JVM_Yield");
3075   if (os::dont_yield()) return;
3076   HOTSPOT_THREAD_YIELD();
3077   os::naked_yield();
3078 JVM_END
3079 
3080 static void post_thread_sleep_event(EventThreadSleep* event, jlong millis) {
3081   assert(event != NULL, "invariant");
3082   assert(event->should_commit(), "invariant");
3083   event->set_time(millis);
3084   event->commit();
3085 }
3086 
3087 JVM_ENTRY(void, JVM_Sleep(JNIEnv* env, jclass threadClass, jlong millis))
3088   JVMWrapper("JVM_Sleep");
3089 
3090   if (millis < 0) {
3091     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "timeout value is negative");
3092   }
3093 
3094   if (thread->is_interrupted(true) && !HAS_PENDING_EXCEPTION) {
3095     THROW_MSG(vmSymbols::java_lang_InterruptedException(), "sleep interrupted");
3096   }
3097 
3098   // Save current thread state and restore it at the end of this block.
3099   // And set new thread state to SLEEPING.
3100   JavaThreadSleepState jtss(thread);
3101 
3102   HOTSPOT_THREAD_SLEEP_BEGIN(millis);
3103   EventThreadSleep event;
3104 
3105   if (millis == 0) {
3106     os::naked_yield();
3107   } else {
3108     ThreadState old_state = thread->osthread()->get_state();
3109     thread->osthread()->set_state(SLEEPING);
3110     if (!thread->sleep(millis)) { // interrupted
3111       // An asynchronous exception (e.g., ThreadDeathException) could have been thrown on
3112       // us while we were sleeping. We do not overwrite those.
3113       if (!HAS_PENDING_EXCEPTION) {
3114         if (event.should_commit()) {
3115           post_thread_sleep_event(&event, millis);
3116         }
3117         HOTSPOT_THREAD_SLEEP_END(1);
3118 
3119         // TODO-FIXME: THROW_MSG returns which means we will not call set_state()
3120         // to properly restore the thread state.  That's likely wrong.
3121         THROW_MSG(vmSymbols::java_lang_InterruptedException(), "sleep interrupted");
3122       }
3123     }
3124     thread->osthread()->set_state(old_state);
3125   }
3126   if (event.should_commit()) {
3127     post_thread_sleep_event(&event, millis);
3128   }
3129   HOTSPOT_THREAD_SLEEP_END(0);
3130 JVM_END
3131 
3132 JVM_ENTRY(jobject, JVM_CurrentThread(JNIEnv* env, jclass threadClass))
3133   JVMWrapper("JVM_CurrentThread");
3134   oop jthread = thread->threadObj();
3135   assert (thread != NULL, "no current thread!");
3136   return JNIHandles::make_local(env, jthread);
3137 JVM_END
3138 
3139 JVM_ENTRY(void, JVM_Interrupt(JNIEnv* env, jobject jthread))
3140   JVMWrapper("JVM_Interrupt");
3141 
3142   ThreadsListHandle tlh(thread);
3143   JavaThread* receiver = NULL;
3144   bool is_alive = tlh.cv_internal_thread_to_JavaThread(jthread, &receiver, NULL);
3145   if (is_alive) {
3146     // jthread refers to a live JavaThread.
3147     receiver->interrupt();
3148   }
3149 JVM_END
3150 
3151 
3152 // Return true iff the current thread has locked the object passed in
3153 
3154 JVM_ENTRY(jboolean, JVM_HoldsLock(JNIEnv* env, jclass threadClass, jobject obj))
3155   JVMWrapper("JVM_HoldsLock");
3156   assert(THREAD->is_Java_thread(), "sanity check");
3157   if (obj == NULL) {
3158     THROW_(vmSymbols::java_lang_NullPointerException(), JNI_FALSE);
3159   }
3160   Handle h_obj(THREAD, JNIHandles::resolve(obj));
3161   return ObjectSynchronizer::current_thread_holds_lock((JavaThread*)THREAD, h_obj);
3162 JVM_END
3163 
3164 
3165 JVM_ENTRY(void, JVM_DumpAllStacks(JNIEnv* env, jclass))
3166   JVMWrapper("JVM_DumpAllStacks");
3167   VM_PrintThreads op;
3168   VMThread::execute(&op);
3169   if (JvmtiExport::should_post_data_dump()) {
3170     JvmtiExport::post_data_dump();
3171   }
3172 JVM_END
3173 
3174 JVM_ENTRY(void, JVM_SetNativeThreadName(JNIEnv* env, jobject jthread, jstring name))
3175   JVMWrapper("JVM_SetNativeThreadName");
3176 
3177   // We don't use a ThreadsListHandle here because the current thread
3178   // must be alive.
3179   oop java_thread = JNIHandles::resolve_non_null(jthread);
3180   JavaThread* thr = java_lang_Thread::thread(java_thread);
3181   if (thread == thr && !thr->has_attached_via_jni()) {
3182     // Thread naming is only supported for the current thread and
3183     // we don't set the name of an attached thread to avoid stepping
3184     // on other programs.
3185     ResourceMark rm(thread);
3186     const char *thread_name = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(name));
3187     os::set_native_thread_name(thread_name);
3188   }
3189 JVM_END
3190 
3191 // java.lang.SecurityManager ///////////////////////////////////////////////////////////////////////
3192 
3193 JVM_ENTRY(jobjectArray, JVM_GetClassContext(JNIEnv *env))
3194   JVMWrapper("JVM_GetClassContext");
3195   ResourceMark rm(THREAD);
3196   JvmtiVMObjectAllocEventCollector oam;
3197   vframeStream vfst(thread);
3198 
3199   if (SystemDictionary::reflect_CallerSensitive_klass() != NULL) {
3200     // This must only be called from SecurityManager.getClassContext
3201     Method* m = vfst.method();
3202     if (!(m->method_holder() == SystemDictionary::SecurityManager_klass() &&
3203           m->name()          == vmSymbols::getClassContext_name() &&
3204           m->signature()     == vmSymbols::void_class_array_signature())) {
3205       THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), "JVM_GetClassContext must only be called from SecurityManager.getClassContext");
3206     }
3207   }
3208 
3209   // Collect method holders
3210   GrowableArray<Klass*>* klass_array = new GrowableArray<Klass*>();
3211   for (; !vfst.at_end(); vfst.security_next()) {
3212     Method* m = vfst.method();
3213     // Native frames are not returned
3214     if (!m->is_ignored_by_security_stack_walk() && !m->is_native()) {
3215       Klass* holder = m->method_holder();
3216       assert(holder->is_klass(), "just checking");
3217       klass_array->append(holder);
3218     }
3219   }
3220 
3221   // Create result array of type [Ljava/lang/Class;
3222   objArrayOop result = oopFactory::new_objArray(SystemDictionary::Class_klass(), klass_array->length(), CHECK_NULL);
3223   // Fill in mirrors corresponding to method holders
3224   for (int i = 0; i < klass_array->length(); i++) {
3225     result->obj_at_put(i, klass_array->at(i)->java_mirror());
3226   }
3227 
3228   return (jobjectArray) JNIHandles::make_local(env, result);
3229 JVM_END
3230 
3231 
3232 // java.lang.Package ////////////////////////////////////////////////////////////////
3233 
3234 
3235 JVM_ENTRY(jstring, JVM_GetSystemPackage(JNIEnv *env, jstring name))
3236   JVMWrapper("JVM_GetSystemPackage");
3237   ResourceMark rm(THREAD);
3238   JvmtiVMObjectAllocEventCollector oam;
3239   char* str = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(name));
3240   oop result = ClassLoader::get_system_package(str, CHECK_NULL);
3241   return (jstring) JNIHandles::make_local(result);
3242 JVM_END
3243 
3244 
3245 JVM_ENTRY(jobjectArray, JVM_GetSystemPackages(JNIEnv *env))
3246   JVMWrapper("JVM_GetSystemPackages");
3247   JvmtiVMObjectAllocEventCollector oam;
3248   objArrayOop result = ClassLoader::get_system_packages(CHECK_NULL);
3249   return (jobjectArray) JNIHandles::make_local(result);
3250 JVM_END
3251 
3252 
3253 // java.lang.ref.Reference ///////////////////////////////////////////////////////////////
3254 
3255 
3256 JVM_ENTRY(jobject, JVM_GetAndClearReferencePendingList(JNIEnv* env))
3257   JVMWrapper("JVM_GetAndClearReferencePendingList");
3258 
3259   MonitorLocker ml(Heap_lock);
3260   oop ref = Universe::reference_pending_list();
3261   if (ref != NULL) {
3262     Universe::set_reference_pending_list(NULL);
3263   }
3264   return JNIHandles::make_local(env, ref);
3265 JVM_END
3266 
3267 JVM_ENTRY(jboolean, JVM_HasReferencePendingList(JNIEnv* env))
3268   JVMWrapper("JVM_HasReferencePendingList");
3269   MonitorLocker ml(Heap_lock);
3270   return Universe::has_reference_pending_list();
3271 JVM_END
3272 
3273 JVM_ENTRY(void, JVM_WaitForReferencePendingList(JNIEnv* env))
3274   JVMWrapper("JVM_WaitForReferencePendingList");
3275   MonitorLocker ml(Heap_lock);
3276   while (!Universe::has_reference_pending_list()) {
3277     ml.wait();
3278   }
3279 JVM_END
3280 
3281 
3282 // ObjectInputStream ///////////////////////////////////////////////////////////////
3283 
3284 // Return the first user-defined class loader up the execution stack, or null
3285 // if only code from the bootstrap or platform class loader is on the stack.
3286 
3287 JVM_ENTRY(jobject, JVM_LatestUserDefinedLoader(JNIEnv *env))
3288   for (vframeStream vfst(thread); !vfst.at_end(); vfst.next()) {
3289     vfst.skip_reflection_related_frames(); // Only needed for 1.4 reflection
3290     oop loader = vfst.method()->method_holder()->class_loader();
3291     if (loader != NULL && !SystemDictionary::is_platform_class_loader(loader)) {
3292       return JNIHandles::make_local(env, loader);
3293     }
3294   }
3295   return NULL;
3296 JVM_END
3297 
3298 
3299 // Array ///////////////////////////////////////////////////////////////////////////////////////////
3300 
3301 
3302 // resolve array handle and check arguments
3303 static inline arrayOop check_array(JNIEnv *env, jobject arr, bool type_array_only, TRAPS) {
3304   if (arr == NULL) {
3305     THROW_0(vmSymbols::java_lang_NullPointerException());
3306   }
3307   oop a = JNIHandles::resolve_non_null(arr);
3308   if (!a->is_array()) {
3309     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Argument is not an array");
3310   } else if (type_array_only && !a->is_typeArray()) {
3311     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Argument is not an array of primitive type");
3312   }
3313   return arrayOop(a);
3314 }
3315 
3316 
3317 JVM_ENTRY(jint, JVM_GetArrayLength(JNIEnv *env, jobject arr))
3318   JVMWrapper("JVM_GetArrayLength");
3319   arrayOop a = check_array(env, arr, false, CHECK_0);
3320   return a->length();
3321 JVM_END
3322 
3323 
3324 JVM_ENTRY(jobject, JVM_GetArrayElement(JNIEnv *env, jobject arr, jint index))
3325   JVMWrapper("JVM_Array_Get");
3326   JvmtiVMObjectAllocEventCollector oam;
3327   arrayOop a = check_array(env, arr, false, CHECK_NULL);
3328   jvalue value;
3329   BasicType type = Reflection::array_get(&value, a, index, CHECK_NULL);
3330   oop box = Reflection::box(&value, type, CHECK_NULL);
3331   return JNIHandles::make_local(env, box);
3332 JVM_END
3333 
3334 
3335 JVM_ENTRY(jvalue, JVM_GetPrimitiveArrayElement(JNIEnv *env, jobject arr, jint index, jint wCode))
3336   JVMWrapper("JVM_GetPrimitiveArrayElement");
3337   jvalue value;
3338   value.i = 0; // to initialize value before getting used in CHECK
3339   arrayOop a = check_array(env, arr, true, CHECK_(value));
3340   assert(a->is_typeArray(), "just checking");
3341   BasicType type = Reflection::array_get(&value, a, index, CHECK_(value));
3342   BasicType wide_type = (BasicType) wCode;
3343   if (type != wide_type) {
3344     Reflection::widen(&value, type, wide_type, CHECK_(value));
3345   }
3346   return value;
3347 JVM_END
3348 
3349 
3350 JVM_ENTRY(void, JVM_SetArrayElement(JNIEnv *env, jobject arr, jint index, jobject val))
3351   JVMWrapper("JVM_SetArrayElement");
3352   arrayOop a = check_array(env, arr, false, CHECK);
3353   oop box = JNIHandles::resolve(val);
3354   jvalue value;
3355   value.i = 0; // to initialize value before getting used in CHECK
3356   BasicType value_type;
3357   if (a->is_objArray()) {
3358     // Make sure we do no unbox e.g. java/lang/Integer instances when storing into an object array
3359     value_type = Reflection::unbox_for_regular_object(box, &value);
3360   } else {
3361     value_type = Reflection::unbox_for_primitive(box, &value, CHECK);
3362   }
3363   Reflection::array_set(&value, a, index, value_type, CHECK);
3364 JVM_END
3365 
3366 
3367 JVM_ENTRY(void, JVM_SetPrimitiveArrayElement(JNIEnv *env, jobject arr, jint index, jvalue v, unsigned char vCode))
3368   JVMWrapper("JVM_SetPrimitiveArrayElement");
3369   arrayOop a = check_array(env, arr, true, CHECK);
3370   assert(a->is_typeArray(), "just checking");
3371   BasicType value_type = (BasicType) vCode;
3372   Reflection::array_set(&v, a, index, value_type, CHECK);
3373 JVM_END
3374 
3375 
3376 JVM_ENTRY(jobject, JVM_NewArray(JNIEnv *env, jclass eltClass, jint length))
3377   JVMWrapper("JVM_NewArray");
3378   JvmtiVMObjectAllocEventCollector oam;
3379   oop element_mirror = JNIHandles::resolve(eltClass);
3380   oop result = Reflection::reflect_new_array(element_mirror, length, CHECK_NULL);
3381   return JNIHandles::make_local(env, result);
3382 JVM_END
3383 
3384 
3385 JVM_ENTRY(jobject, JVM_NewMultiArray(JNIEnv *env, jclass eltClass, jintArray dim))
3386   JVMWrapper("JVM_NewMultiArray");
3387   JvmtiVMObjectAllocEventCollector oam;
3388   arrayOop dim_array = check_array(env, dim, true, CHECK_NULL);
3389   oop element_mirror = JNIHandles::resolve(eltClass);
3390   assert(dim_array->is_typeArray(), "just checking");
3391   oop result = Reflection::reflect_new_multi_array(element_mirror, typeArrayOop(dim_array), CHECK_NULL);
3392   return JNIHandles::make_local(env, result);
3393 JVM_END
3394 
3395 
3396 // Library support ///////////////////////////////////////////////////////////////////////////
3397 
3398 JVM_ENTRY_NO_ENV(void*, JVM_LoadLibrary(const char* name))
3399   //%note jvm_ct
3400   JVMWrapper("JVM_LoadLibrary");
3401   char ebuf[1024];
3402   void *load_result;
3403   {
3404     ThreadToNativeFromVM ttnfvm(thread);
3405     load_result = os::dll_load(name, ebuf, sizeof ebuf);
3406   }
3407   if (load_result == NULL) {
3408     char msg[1024];
3409     jio_snprintf(msg, sizeof msg, "%s: %s", name, ebuf);
3410     // Since 'ebuf' may contain a string encoded using
3411     // platform encoding scheme, we need to pass
3412     // Exceptions::unsafe_to_utf8 to the new_exception method
3413     // as the last argument. See bug 6367357.
3414     Handle h_exception =
3415       Exceptions::new_exception(thread,
3416                                 vmSymbols::java_lang_UnsatisfiedLinkError(),
3417                                 msg, Exceptions::unsafe_to_utf8);
3418 
3419     THROW_HANDLE_0(h_exception);
3420   }
3421   return load_result;
3422 JVM_END
3423 
3424 
3425 JVM_LEAF(void, JVM_UnloadLibrary(void* handle))
3426   JVMWrapper("JVM_UnloadLibrary");
3427   os::dll_unload(handle);
3428 JVM_END
3429 
3430 
3431 JVM_LEAF(void*, JVM_FindLibraryEntry(void* handle, const char* name))
3432   JVMWrapper("JVM_FindLibraryEntry");
3433   return os::dll_lookup(handle, name);
3434 JVM_END
3435 
3436 
3437 // JNI version ///////////////////////////////////////////////////////////////////////////////
3438 
3439 JVM_LEAF(jboolean, JVM_IsSupportedJNIVersion(jint version))
3440   JVMWrapper("JVM_IsSupportedJNIVersion");
3441   return Threads::is_supported_jni_version_including_1_1(version);
3442 JVM_END
3443 
3444 
3445 // String support ///////////////////////////////////////////////////////////////////////////
3446 
3447 JVM_ENTRY(jstring, JVM_InternString(JNIEnv *env, jstring str))
3448   JVMWrapper("JVM_InternString");
3449   JvmtiVMObjectAllocEventCollector oam;
3450   if (str == NULL) return NULL;
3451   oop string = JNIHandles::resolve_non_null(str);
3452   oop result = StringTable::intern(string, CHECK_NULL);
3453   return (jstring) JNIHandles::make_local(env, result);
3454 JVM_END
3455 
3456 
3457 // VM Raw monitor support //////////////////////////////////////////////////////////////////////
3458 
3459 // VM Raw monitors (not to be confused with JvmtiRawMonitors) are a simple mutual exclusion
3460 // lock (not actually monitors: no wait/notify) that is exported by the VM for use by JDK
3461 // library code. They may be used by JavaThreads and non-JavaThreads and do not participate
3462 // in the safepoint protocol, thread suspension, thread interruption, or anything of that
3463 // nature. JavaThreads will be "in native" when using this API from JDK code.
3464 
3465 
3466 JNIEXPORT void* JNICALL JVM_RawMonitorCreate(void) {
3467   VM_Exit::block_if_vm_exited();
3468   JVMWrapper("JVM_RawMonitorCreate");
3469   return new os::PlatformMutex();
3470 }
3471 
3472 
3473 JNIEXPORT void JNICALL  JVM_RawMonitorDestroy(void *mon) {
3474   VM_Exit::block_if_vm_exited();
3475   JVMWrapper("JVM_RawMonitorDestroy");
3476   delete ((os::PlatformMutex*) mon);
3477 }
3478 
3479 
3480 JNIEXPORT jint JNICALL JVM_RawMonitorEnter(void *mon) {
3481   VM_Exit::block_if_vm_exited();
3482   JVMWrapper("JVM_RawMonitorEnter");
3483   ((os::PlatformMutex*) mon)->lock();
3484   return 0;
3485 }
3486 
3487 
3488 JNIEXPORT void JNICALL JVM_RawMonitorExit(void *mon) {
3489   VM_Exit::block_if_vm_exited();
3490   JVMWrapper("JVM_RawMonitorExit");
3491   ((os::PlatformMutex*) mon)->unlock();
3492 }
3493 
3494 
3495 // Shared JNI/JVM entry points //////////////////////////////////////////////////////////////
3496 
3497 jclass find_class_from_class_loader(JNIEnv* env, Symbol* name, jboolean init,
3498                                     Handle loader, Handle protection_domain,
3499                                     jboolean throwError, TRAPS) {
3500   // Security Note:
3501   //   The Java level wrapper will perform the necessary security check allowing
3502   //   us to pass the NULL as the initiating class loader.  The VM is responsible for
3503   //   the checkPackageAccess relative to the initiating class loader via the
3504   //   protection_domain. The protection_domain is passed as NULL by the java code
3505   //   if there is no security manager in 3-arg Class.forName().
3506   Klass* klass = SystemDictionary::resolve_or_fail(name, loader, protection_domain, throwError != 0, CHECK_NULL);
3507 
3508   // Check if we should initialize the class
3509   if (init && klass->is_instance_klass()) {
3510     klass->initialize(CHECK_NULL);
3511   }
3512   return (jclass) JNIHandles::make_local(env, klass->java_mirror());
3513 }
3514 
3515 
3516 // Method ///////////////////////////////////////////////////////////////////////////////////////////
3517 
3518 JVM_ENTRY(jobject, JVM_InvokeMethod(JNIEnv *env, jobject method, jobject obj, jobjectArray args0))
3519   JVMWrapper("JVM_InvokeMethod");
3520   Handle method_handle;
3521   if (thread->stack_available((address) &method_handle) >= JVMInvokeMethodSlack) {
3522     method_handle = Handle(THREAD, JNIHandles::resolve(method));
3523     Handle receiver(THREAD, JNIHandles::resolve(obj));
3524     objArrayHandle args = oopFactory::ensure_objArray(JNIHandles::resolve(args0), CHECK_NULL);
3525     oop result = Reflection::invoke_method(method_handle(), receiver, args, CHECK_NULL);
3526     jobject res = JNIHandles::make_local(env, result);
3527     if (JvmtiExport::should_post_vm_object_alloc()) {
3528       oop ret_type = java_lang_reflect_Method::return_type(method_handle());
3529       assert(ret_type != NULL, "sanity check: ret_type oop must not be NULL!");
3530       if (java_lang_Class::is_primitive(ret_type)) {
3531         // Only for primitive type vm allocates memory for java object.
3532         // See box() method.
3533         JvmtiExport::post_vm_object_alloc(JavaThread::current(), result);
3534       }
3535     }
3536     return res;
3537   } else {
3538     THROW_0(vmSymbols::java_lang_StackOverflowError());
3539   }
3540 JVM_END
3541 
3542 
3543 JVM_ENTRY(jobject, JVM_NewInstanceFromConstructor(JNIEnv *env, jobject c, jobjectArray args0))
3544   JVMWrapper("JVM_NewInstanceFromConstructor");
3545   objArrayHandle args = oopFactory::ensure_objArray(JNIHandles::resolve(args0), CHECK_NULL);
3546   oop constructor_mirror = JNIHandles::resolve(c);
3547   oop result = Reflection::invoke_constructor(constructor_mirror, args, CHECK_NULL);
3548   jobject res = JNIHandles::make_local(env, result);
3549   if (JvmtiExport::should_post_vm_object_alloc()) {
3550     JvmtiExport::post_vm_object_alloc(JavaThread::current(), result);
3551   }
3552   return res;
3553 JVM_END
3554 
3555 // Atomic ///////////////////////////////////////////////////////////////////////////////////////////
3556 
3557 JVM_LEAF(jboolean, JVM_SupportsCX8())
3558   JVMWrapper("JVM_SupportsCX8");
3559   return VM_Version::supports_cx8();
3560 JVM_END
3561 
3562 JVM_ENTRY(void, JVM_InitializeFromArchive(JNIEnv* env, jclass cls))
3563   JVMWrapper("JVM_InitializeFromArchive");
3564   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve(cls));
3565   assert(k->is_klass(), "just checking");
3566   HeapShared::initialize_from_archived_subgraph(k);
3567 JVM_END
3568 
3569 // Returns an array of all live Thread objects (VM internal JavaThreads,
3570 // jvmti agent threads, and JNI attaching threads  are skipped)
3571 // See CR 6404306 regarding JNI attaching threads
3572 JVM_ENTRY(jobjectArray, JVM_GetAllThreads(JNIEnv *env, jclass dummy))
3573   ResourceMark rm(THREAD);
3574   ThreadsListEnumerator tle(THREAD, false, false);
3575   JvmtiVMObjectAllocEventCollector oam;
3576 
3577   int num_threads = tle.num_threads();
3578   objArrayOop r = oopFactory::new_objArray(SystemDictionary::Thread_klass(), num_threads, CHECK_NULL);
3579   objArrayHandle threads_ah(THREAD, r);
3580 
3581   for (int i = 0; i < num_threads; i++) {
3582     Handle h = tle.get_threadObj(i);
3583     threads_ah->obj_at_put(i, h());
3584   }
3585 
3586   return (jobjectArray) JNIHandles::make_local(env, threads_ah());
3587 JVM_END
3588 
3589 
3590 // Support for java.lang.Thread.getStackTrace() and getAllStackTraces() methods
3591 // Return StackTraceElement[][], each element is the stack trace of a thread in
3592 // the corresponding entry in the given threads array
3593 JVM_ENTRY(jobjectArray, JVM_DumpThreads(JNIEnv *env, jclass threadClass, jobjectArray threads))
3594   JVMWrapper("JVM_DumpThreads");
3595   JvmtiVMObjectAllocEventCollector oam;
3596 
3597   // Check if threads is null
3598   if (threads == NULL) {
3599     THROW_(vmSymbols::java_lang_NullPointerException(), 0);
3600   }
3601 
3602   objArrayOop a = objArrayOop(JNIHandles::resolve_non_null(threads));
3603   objArrayHandle ah(THREAD, a);
3604   int num_threads = ah->length();
3605   // check if threads is non-empty array
3606   if (num_threads == 0) {
3607     THROW_(vmSymbols::java_lang_IllegalArgumentException(), 0);
3608   }
3609 
3610   // check if threads is not an array of objects of Thread class
3611   Klass* k = ObjArrayKlass::cast(ah->klass())->element_klass();
3612   if (k != SystemDictionary::Thread_klass()) {
3613     THROW_(vmSymbols::java_lang_IllegalArgumentException(), 0);
3614   }
3615 
3616   ResourceMark rm(THREAD);
3617 
3618   GrowableArray<instanceHandle>* thread_handle_array = new GrowableArray<instanceHandle>(num_threads);
3619   for (int i = 0; i < num_threads; i++) {
3620     oop thread_obj = ah->obj_at(i);
3621     instanceHandle h(THREAD, (instanceOop) thread_obj);
3622     thread_handle_array->append(h);
3623   }
3624 
3625   // The JavaThread references in thread_handle_array are validated
3626   // in VM_ThreadDump::doit().
3627   Handle stacktraces = ThreadService::dump_stack_traces(thread_handle_array, num_threads, CHECK_NULL);
3628   return (jobjectArray)JNIHandles::make_local(env, stacktraces());
3629 
3630 JVM_END
3631 
3632 // JVM monitoring and management support
3633 JVM_ENTRY_NO_ENV(void*, JVM_GetManagement(jint version))
3634   return Management::get_jmm_interface(version);
3635 JVM_END
3636 
3637 // com.sun.tools.attach.VirtualMachine agent properties support
3638 //
3639 // Initialize the agent properties with the properties maintained in the VM
3640 JVM_ENTRY(jobject, JVM_InitAgentProperties(JNIEnv *env, jobject properties))
3641   JVMWrapper("JVM_InitAgentProperties");
3642   ResourceMark rm;
3643 
3644   Handle props(THREAD, JNIHandles::resolve_non_null(properties));
3645 
3646   PUTPROP(props, "sun.java.command", Arguments::java_command());
3647   PUTPROP(props, "sun.jvm.flags", Arguments::jvm_flags());
3648   PUTPROP(props, "sun.jvm.args", Arguments::jvm_args());
3649   return properties;
3650 JVM_END
3651 
3652 JVM_ENTRY(jobjectArray, JVM_GetEnclosingMethodInfo(JNIEnv *env, jclass ofClass))
3653 {
3654   JVMWrapper("JVM_GetEnclosingMethodInfo");
3655   JvmtiVMObjectAllocEventCollector oam;
3656 
3657   if (ofClass == NULL) {
3658     return NULL;
3659   }
3660   Handle mirror(THREAD, JNIHandles::resolve_non_null(ofClass));
3661   // Special handling for primitive objects
3662   if (java_lang_Class::is_primitive(mirror())) {
3663     return NULL;
3664   }
3665   Klass* k = java_lang_Class::as_Klass(mirror());
3666   if (!k->is_instance_klass()) {
3667     return NULL;
3668   }
3669   InstanceKlass* ik = InstanceKlass::cast(k);
3670   int encl_method_class_idx = ik->enclosing_method_class_index();
3671   if (encl_method_class_idx == 0) {
3672     return NULL;
3673   }
3674   objArrayOop dest_o = oopFactory::new_objArray(SystemDictionary::Object_klass(), 3, CHECK_NULL);
3675   objArrayHandle dest(THREAD, dest_o);
3676   Klass* enc_k = ik->constants()->klass_at(encl_method_class_idx, CHECK_NULL);
3677   dest->obj_at_put(0, enc_k->java_mirror());
3678   int encl_method_method_idx = ik->enclosing_method_method_index();
3679   if (encl_method_method_idx != 0) {
3680     Symbol* sym = ik->constants()->symbol_at(
3681                         extract_low_short_from_int(
3682                           ik->constants()->name_and_type_at(encl_method_method_idx)));
3683     Handle str = java_lang_String::create_from_symbol(sym, CHECK_NULL);
3684     dest->obj_at_put(1, str());
3685     sym = ik->constants()->symbol_at(
3686               extract_high_short_from_int(
3687                 ik->constants()->name_and_type_at(encl_method_method_idx)));
3688     str = java_lang_String::create_from_symbol(sym, CHECK_NULL);
3689     dest->obj_at_put(2, str());
3690   }
3691   return (jobjectArray) JNIHandles::make_local(dest());
3692 }
3693 JVM_END
3694 
3695 // Returns an array of java.lang.String objects containing the input arguments to the VM.
3696 JVM_ENTRY(jobjectArray, JVM_GetVmArguments(JNIEnv *env))
3697   ResourceMark rm(THREAD);
3698 
3699   if (Arguments::num_jvm_args() == 0 && Arguments::num_jvm_flags() == 0) {
3700     return NULL;
3701   }
3702 
3703   char** vm_flags = Arguments::jvm_flags_array();
3704   char** vm_args = Arguments::jvm_args_array();
3705   int num_flags = Arguments::num_jvm_flags();
3706   int num_args = Arguments::num_jvm_args();
3707 
3708   InstanceKlass* ik = SystemDictionary::String_klass();
3709   objArrayOop r = oopFactory::new_objArray(ik, num_args + num_flags, CHECK_NULL);
3710   objArrayHandle result_h(THREAD, r);
3711 
3712   int index = 0;
3713   for (int j = 0; j < num_flags; j++, index++) {
3714     Handle h = java_lang_String::create_from_platform_dependent_str(vm_flags[j], CHECK_NULL);
3715     result_h->obj_at_put(index, h());
3716   }
3717   for (int i = 0; i < num_args; i++, index++) {
3718     Handle h = java_lang_String::create_from_platform_dependent_str(vm_args[i], CHECK_NULL);
3719     result_h->obj_at_put(index, h());
3720   }
3721   return (jobjectArray) JNIHandles::make_local(env, result_h());
3722 JVM_END
3723 
3724 JVM_ENTRY_NO_ENV(jint, JVM_FindSignal(const char *name))
3725   return os::get_signal_number(name);
3726 JVM_END