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