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