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