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