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