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, CHECK_0);
 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, CHECK);
 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->oop_is_instance()) {
1115     size = InstanceKlass::cast(klass())->local_interfaces()->length();
1116   } else {
1117     assert(klass->oop_is_objArray() || klass->oop_is_typeArray(), "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->oop_is_instance()) {
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->oop_is_instance(),
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->oop_is_instance()) {
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 = InstanceKlass::cast(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->oop_is_array() ? 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))->oop_is_instance()) {
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))->oop_is_instance()) {
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)->oop_is_instance()) {
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->oop_is_instance()) {
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->oop_is_instance()) {
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->oop_is_instance()) {
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))->oop_is_array()) {
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))->oop_is_array()) {
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->oop_is_instance()) {
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->oop_is_instance(), "must be an instance klass");
2229   if (! k->oop_is_instance()) 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->oop_is_instance()) {
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   if (!k->oop_is_instance())
2289     return 0;
2290   return InstanceKlass::cast(k)->constants()->length();
2291 JVM_END
2292 
2293 
2294 JVM_QUICK_ENTRY(jint, JVM_GetClassFieldsCount(JNIEnv *env, jclass cls))
2295   JVMWrapper("JVM_GetClassFieldsCount");
2296   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2297   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2298   if (!k->oop_is_instance())
2299     return 0;
2300   return InstanceKlass::cast(k)->java_fields_count();
2301 JVM_END
2302 
2303 
2304 JVM_QUICK_ENTRY(jint, JVM_GetClassMethodsCount(JNIEnv *env, jclass cls))
2305   JVMWrapper("JVM_GetClassMethodsCount");
2306   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2307   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2308   if (!k->oop_is_instance())
2309     return 0;
2310   return InstanceKlass::cast(k)->methods()->length();
2311 JVM_END
2312 
2313 
2314 // The following methods, used for the verifier, are never called with
2315 // array klasses, so a direct cast to InstanceKlass is safe.
2316 // Typically, these methods are called in a loop with bounds determined
2317 // by the results of JVM_GetClass{Fields,Methods}Count, which return
2318 // zero for arrays.
2319 JVM_QUICK_ENTRY(void, JVM_GetMethodIxExceptionIndexes(JNIEnv *env, jclass cls, jint method_index, unsigned short *exceptions))
2320   JVMWrapper("JVM_GetMethodIxExceptionIndexes");
2321   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2322   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2323   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2324   int length = method->checked_exceptions_length();
2325   if (length > 0) {
2326     CheckedExceptionElement* table= method->checked_exceptions_start();
2327     for (int i = 0; i < length; i++) {
2328       exceptions[i] = table[i].class_cp_index;
2329     }
2330   }
2331 JVM_END
2332 
2333 
2334 JVM_QUICK_ENTRY(jint, JVM_GetMethodIxExceptionsCount(JNIEnv *env, jclass cls, jint method_index))
2335   JVMWrapper("JVM_GetMethodIxExceptionsCount");
2336   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2337   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2338   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2339   return method->checked_exceptions_length();
2340 JVM_END
2341 
2342 
2343 JVM_QUICK_ENTRY(void, JVM_GetMethodIxByteCode(JNIEnv *env, jclass cls, jint method_index, unsigned char *code))
2344   JVMWrapper("JVM_GetMethodIxByteCode");
2345   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2346   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2347   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2348   memcpy(code, method->code_base(), method->code_size());
2349 JVM_END
2350 
2351 
2352 JVM_QUICK_ENTRY(jint, JVM_GetMethodIxByteCodeLength(JNIEnv *env, jclass cls, jint method_index))
2353   JVMWrapper("JVM_GetMethodIxByteCodeLength");
2354   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2355   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2356   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2357   return method->code_size();
2358 JVM_END
2359 
2360 
2361 JVM_QUICK_ENTRY(void, JVM_GetMethodIxExceptionTableEntry(JNIEnv *env, jclass cls, jint method_index, jint entry_index, JVM_ExceptionTableEntryType *entry))
2362   JVMWrapper("JVM_GetMethodIxExceptionTableEntry");
2363   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2364   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2365   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2366   ExceptionTable extable(method);
2367   entry->start_pc   = extable.start_pc(entry_index);
2368   entry->end_pc     = extable.end_pc(entry_index);
2369   entry->handler_pc = extable.handler_pc(entry_index);
2370   entry->catchType  = extable.catch_type_index(entry_index);
2371 JVM_END
2372 
2373 
2374 JVM_QUICK_ENTRY(jint, JVM_GetMethodIxExceptionTableLength(JNIEnv *env, jclass cls, int method_index))
2375   JVMWrapper("JVM_GetMethodIxExceptionTableLength");
2376   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2377   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2378   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2379   return method->exception_table_length();
2380 JVM_END
2381 
2382 
2383 JVM_QUICK_ENTRY(jint, JVM_GetMethodIxModifiers(JNIEnv *env, jclass cls, int method_index))
2384   JVMWrapper("JVM_GetMethodIxModifiers");
2385   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2386   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2387   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2388   return method->access_flags().as_int() & JVM_RECOGNIZED_METHOD_MODIFIERS;
2389 JVM_END
2390 
2391 
2392 JVM_QUICK_ENTRY(jint, JVM_GetFieldIxModifiers(JNIEnv *env, jclass cls, int field_index))
2393   JVMWrapper("JVM_GetFieldIxModifiers");
2394   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2395   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2396   return InstanceKlass::cast(k)->field_access_flags(field_index) & JVM_RECOGNIZED_FIELD_MODIFIERS;
2397 JVM_END
2398 
2399 
2400 JVM_QUICK_ENTRY(jint, JVM_GetMethodIxLocalsCount(JNIEnv *env, jclass cls, int method_index))
2401   JVMWrapper("JVM_GetMethodIxLocalsCount");
2402   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2403   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2404   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2405   return method->max_locals();
2406 JVM_END
2407 
2408 
2409 JVM_QUICK_ENTRY(jint, JVM_GetMethodIxArgsSize(JNIEnv *env, jclass cls, int method_index))
2410   JVMWrapper("JVM_GetMethodIxArgsSize");
2411   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2412   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2413   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2414   return method->size_of_parameters();
2415 JVM_END
2416 
2417 
2418 JVM_QUICK_ENTRY(jint, JVM_GetMethodIxMaxStack(JNIEnv *env, jclass cls, int method_index))
2419   JVMWrapper("JVM_GetMethodIxMaxStack");
2420   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2421   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2422   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2423   return method->verifier_max_stack();
2424 JVM_END
2425 
2426 
2427 JVM_QUICK_ENTRY(jboolean, JVM_IsConstructorIx(JNIEnv *env, jclass cls, int method_index))
2428   JVMWrapper("JVM_IsConstructorIx");
2429   ResourceMark rm(THREAD);
2430   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2431   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2432   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2433   return method->name() == vmSymbols::object_initializer_name();
2434 JVM_END
2435 
2436 
2437 JVM_QUICK_ENTRY(jboolean, JVM_IsVMGeneratedMethodIx(JNIEnv *env, jclass cls, int method_index))
2438   JVMWrapper("JVM_IsVMGeneratedMethodIx");
2439   ResourceMark rm(THREAD);
2440   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2441   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2442   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2443   return method->is_overpass();
2444 JVM_END
2445 
2446 JVM_ENTRY(const char*, JVM_GetMethodIxNameUTF(JNIEnv *env, jclass cls, jint method_index))
2447   JVMWrapper("JVM_GetMethodIxIxUTF");
2448   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2449   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2450   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2451   return method->name()->as_utf8();
2452 JVM_END
2453 
2454 
2455 JVM_ENTRY(const char*, JVM_GetMethodIxSignatureUTF(JNIEnv *env, jclass cls, jint method_index))
2456   JVMWrapper("JVM_GetMethodIxSignatureUTF");
2457   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2458   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2459   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2460   return method->signature()->as_utf8();
2461 JVM_END
2462 
2463 /**
2464  * All of these JVM_GetCP-xxx methods are used by the old verifier to
2465  * read entries in the constant pool.  Since the old verifier always
2466  * works on a copy of the code, it will not see any rewriting that
2467  * may possibly occur in the middle of verification.  So it is important
2468  * that nothing it calls tries to use the cpCache instead of the raw
2469  * constant pool, so we must use cp->uncached_x methods when appropriate.
2470  */
2471 JVM_ENTRY(const char*, JVM_GetCPFieldNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2472   JVMWrapper("JVM_GetCPFieldNameUTF");
2473   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2474   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2475   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2476   switch (cp->tag_at(cp_index).value()) {
2477     case JVM_CONSTANT_Fieldref:
2478       return cp->uncached_name_ref_at(cp_index)->as_utf8();
2479     default:
2480       fatal("JVM_GetCPFieldNameUTF: illegal constant");
2481   }
2482   ShouldNotReachHere();
2483   return NULL;
2484 JVM_END
2485 
2486 
2487 JVM_ENTRY(const char*, JVM_GetCPMethodNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2488   JVMWrapper("JVM_GetCPMethodNameUTF");
2489   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2490   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2491   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2492   switch (cp->tag_at(cp_index).value()) {
2493     case JVM_CONSTANT_InterfaceMethodref:
2494     case JVM_CONSTANT_Methodref:
2495     case JVM_CONSTANT_NameAndType:  // for invokedynamic
2496       return cp->uncached_name_ref_at(cp_index)->as_utf8();
2497     default:
2498       fatal("JVM_GetCPMethodNameUTF: illegal constant");
2499   }
2500   ShouldNotReachHere();
2501   return NULL;
2502 JVM_END
2503 
2504 
2505 JVM_ENTRY(const char*, JVM_GetCPMethodSignatureUTF(JNIEnv *env, jclass cls, jint cp_index))
2506   JVMWrapper("JVM_GetCPMethodSignatureUTF");
2507   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2508   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2509   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2510   switch (cp->tag_at(cp_index).value()) {
2511     case JVM_CONSTANT_InterfaceMethodref:
2512     case JVM_CONSTANT_Methodref:
2513     case JVM_CONSTANT_NameAndType:  // for invokedynamic
2514       return cp->uncached_signature_ref_at(cp_index)->as_utf8();
2515     default:
2516       fatal("JVM_GetCPMethodSignatureUTF: illegal constant");
2517   }
2518   ShouldNotReachHere();
2519   return NULL;
2520 JVM_END
2521 
2522 
2523 JVM_ENTRY(const char*, JVM_GetCPFieldSignatureUTF(JNIEnv *env, jclass cls, jint cp_index))
2524   JVMWrapper("JVM_GetCPFieldSignatureUTF");
2525   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2526   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2527   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2528   switch (cp->tag_at(cp_index).value()) {
2529     case JVM_CONSTANT_Fieldref:
2530       return cp->uncached_signature_ref_at(cp_index)->as_utf8();
2531     default:
2532       fatal("JVM_GetCPFieldSignatureUTF: illegal constant");
2533   }
2534   ShouldNotReachHere();
2535   return NULL;
2536 JVM_END
2537 
2538 
2539 JVM_ENTRY(const char*, JVM_GetCPClassNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2540   JVMWrapper("JVM_GetCPClassNameUTF");
2541   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2542   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2543   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2544   Symbol* classname = cp->klass_name_at(cp_index);
2545   return classname->as_utf8();
2546 JVM_END
2547 
2548 
2549 JVM_ENTRY(const char*, JVM_GetCPFieldClassNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2550   JVMWrapper("JVM_GetCPFieldClassNameUTF");
2551   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2552   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2553   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2554   switch (cp->tag_at(cp_index).value()) {
2555     case JVM_CONSTANT_Fieldref: {
2556       int class_index = cp->uncached_klass_ref_index_at(cp_index);
2557       Symbol* classname = cp->klass_name_at(class_index);
2558       return classname->as_utf8();
2559     }
2560     default:
2561       fatal("JVM_GetCPFieldClassNameUTF: illegal constant");
2562   }
2563   ShouldNotReachHere();
2564   return NULL;
2565 JVM_END
2566 
2567 
2568 JVM_ENTRY(const char*, JVM_GetCPMethodClassNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2569   JVMWrapper("JVM_GetCPMethodClassNameUTF");
2570   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2571   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2572   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2573   switch (cp->tag_at(cp_index).value()) {
2574     case JVM_CONSTANT_Methodref:
2575     case JVM_CONSTANT_InterfaceMethodref: {
2576       int class_index = cp->uncached_klass_ref_index_at(cp_index);
2577       Symbol* classname = cp->klass_name_at(class_index);
2578       return classname->as_utf8();
2579     }
2580     default:
2581       fatal("JVM_GetCPMethodClassNameUTF: illegal constant");
2582   }
2583   ShouldNotReachHere();
2584   return NULL;
2585 JVM_END
2586 
2587 
2588 JVM_ENTRY(jint, JVM_GetCPFieldModifiers(JNIEnv *env, jclass cls, int cp_index, jclass called_cls))
2589   JVMWrapper("JVM_GetCPFieldModifiers");
2590   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2591   Klass* k_called = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(called_cls));
2592   k        = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2593   k_called = JvmtiThreadState::class_to_verify_considering_redefinition(k_called, thread);
2594   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2595   ConstantPool* cp_called = InstanceKlass::cast(k_called)->constants();
2596   switch (cp->tag_at(cp_index).value()) {
2597     case JVM_CONSTANT_Fieldref: {
2598       Symbol* name      = cp->uncached_name_ref_at(cp_index);
2599       Symbol* signature = cp->uncached_signature_ref_at(cp_index);
2600       for (JavaFieldStream fs(k_called); !fs.done(); fs.next()) {
2601         if (fs.name() == name && fs.signature() == signature) {
2602           return fs.access_flags().as_short() & JVM_RECOGNIZED_FIELD_MODIFIERS;
2603         }
2604       }
2605       return -1;
2606     }
2607     default:
2608       fatal("JVM_GetCPFieldModifiers: illegal constant");
2609   }
2610   ShouldNotReachHere();
2611   return 0;
2612 JVM_END
2613 
2614 
2615 JVM_QUICK_ENTRY(jint, JVM_GetCPMethodModifiers(JNIEnv *env, jclass cls, int cp_index, jclass called_cls))
2616   JVMWrapper("JVM_GetCPMethodModifiers");
2617   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2618   Klass* k_called = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(called_cls));
2619   k        = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2620   k_called = JvmtiThreadState::class_to_verify_considering_redefinition(k_called, thread);
2621   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2622   switch (cp->tag_at(cp_index).value()) {
2623     case JVM_CONSTANT_Methodref:
2624     case JVM_CONSTANT_InterfaceMethodref: {
2625       Symbol* name      = cp->uncached_name_ref_at(cp_index);
2626       Symbol* signature = cp->uncached_signature_ref_at(cp_index);
2627       Array<Method*>* methods = InstanceKlass::cast(k_called)->methods();
2628       int methods_count = methods->length();
2629       for (int i = 0; i < methods_count; i++) {
2630         Method* method = methods->at(i);
2631         if (method->name() == name && method->signature() == signature) {
2632             return method->access_flags().as_int() & JVM_RECOGNIZED_METHOD_MODIFIERS;
2633         }
2634       }
2635       return -1;
2636     }
2637     default:
2638       fatal("JVM_GetCPMethodModifiers: illegal constant");
2639   }
2640   ShouldNotReachHere();
2641   return 0;
2642 JVM_END
2643 
2644 
2645 // Misc //////////////////////////////////////////////////////////////////////////////////////////////
2646 
2647 JVM_LEAF(void, JVM_ReleaseUTF(const char *utf))
2648   // So long as UTF8::convert_to_utf8 returns resource strings, we don't have to do anything
2649 JVM_END
2650 
2651 
2652 JVM_ENTRY(jboolean, JVM_IsSameClassPackage(JNIEnv *env, jclass class1, jclass class2))
2653   JVMWrapper("JVM_IsSameClassPackage");
2654   oop class1_mirror = JNIHandles::resolve_non_null(class1);
2655   oop class2_mirror = JNIHandles::resolve_non_null(class2);
2656   Klass* klass1 = java_lang_Class::as_Klass(class1_mirror);
2657   Klass* klass2 = java_lang_Class::as_Klass(class2_mirror);
2658   return (jboolean) Reflection::is_same_class_package(klass1, klass2);
2659 JVM_END
2660 
2661 // Printing support //////////////////////////////////////////////////
2662 extern "C" {
2663 
2664 ATTRIBUTE_PRINTF(3, 0)
2665 int jio_vsnprintf(char *str, size_t count, const char *fmt, va_list args) {
2666   // see bug 4399518, 4417214
2667   if ((intptr_t)count <= 0) return -1;
2668 
2669   int result = vsnprintf(str, count, fmt, args);
2670   // Note: on truncation vsnprintf(3) on Unix returns numbers of
2671   // characters which would have been written had the buffer been large
2672   // enough; on Windows, it returns -1. We handle both cases here and
2673   // always return -1, and perform null termination.
2674   if ((result > 0 && (size_t)result >= count) || result == -1) {
2675     str[count - 1] = '\0';
2676     result = -1;
2677   }
2678 
2679   return result;
2680 }
2681 
2682 ATTRIBUTE_PRINTF(3, 0)
2683 int jio_snprintf(char *str, size_t count, const char *fmt, ...) {
2684   va_list args;
2685   int len;
2686   va_start(args, fmt);
2687   len = jio_vsnprintf(str, count, fmt, args);
2688   va_end(args);
2689   return len;
2690 }
2691 
2692 ATTRIBUTE_PRINTF(2,3)
2693 int jio_fprintf(FILE* f, const char *fmt, ...) {
2694   int len;
2695   va_list args;
2696   va_start(args, fmt);
2697   len = jio_vfprintf(f, fmt, args);
2698   va_end(args);
2699   return len;
2700 }
2701 
2702 ATTRIBUTE_PRINTF(2, 0)
2703 int jio_vfprintf(FILE* f, const char *fmt, va_list args) {
2704   if (Arguments::vfprintf_hook() != NULL) {
2705      return Arguments::vfprintf_hook()(f, fmt, args);
2706   } else {
2707     return vfprintf(f, fmt, args);
2708   }
2709 }
2710 
2711 ATTRIBUTE_PRINTF(1, 2)
2712 JNIEXPORT int jio_printf(const char *fmt, ...) {
2713   int len;
2714   va_list args;
2715   va_start(args, fmt);
2716   len = jio_vfprintf(defaultStream::output_stream(), fmt, args);
2717   va_end(args);
2718   return len;
2719 }
2720 
2721 
2722 // HotSpot specific jio method
2723 void jio_print(const char* s) {
2724   // Try to make this function as atomic as possible.
2725   if (Arguments::vfprintf_hook() != NULL) {
2726     jio_fprintf(defaultStream::output_stream(), "%s", s);
2727   } else {
2728     // Make an unused local variable to avoid warning from gcc 4.x compiler.
2729     size_t count = ::write(defaultStream::output_fd(), s, (int)strlen(s));
2730   }
2731 }
2732 
2733 } // Extern C
2734 
2735 // java.lang.Thread //////////////////////////////////////////////////////////////////////////////
2736 
2737 // In most of the JVM Thread support functions we need to be sure to lock the Threads_lock
2738 // to prevent the target thread from exiting after we have a pointer to the C++ Thread or
2739 // OSThread objects.  The exception to this rule is when the target object is the thread
2740 // doing the operation, in which case we know that the thread won't exit until the
2741 // operation is done (all exits being voluntary).  There are a few cases where it is
2742 // rather silly to do operations on yourself, like resuming yourself or asking whether
2743 // you are alive.  While these can still happen, they are not subject to deadlocks if
2744 // the lock is held while the operation occurs (this is not the case for suspend, for
2745 // instance), and are very unlikely.  Because IsAlive needs to be fast and its
2746 // implementation is local to this file, we always lock Threads_lock for that one.
2747 
2748 static void thread_entry(JavaThread* thread, TRAPS) {
2749   HandleMark hm(THREAD);
2750   Handle obj(THREAD, thread->threadObj());
2751   JavaValue result(T_VOID);
2752   JavaCalls::call_virtual(&result,
2753                           obj,
2754                           KlassHandle(THREAD, SystemDictionary::Thread_klass()),
2755                           vmSymbols::run_method_name(),
2756                           vmSymbols::void_method_signature(),
2757                           THREAD);
2758 }
2759 
2760 
2761 JVM_ENTRY(void, JVM_StartThread(JNIEnv* env, jobject jthread))
2762   JVMWrapper("JVM_StartThread");
2763   JavaThread *native_thread = NULL;
2764 
2765   // We cannot hold the Threads_lock when we throw an exception,
2766   // due to rank ordering issues. Example:  we might need to grab the
2767   // Heap_lock while we construct the exception.
2768   bool throw_illegal_thread_state = false;
2769 
2770   // We must release the Threads_lock before we can post a jvmti event
2771   // in Thread::start.
2772   {
2773     // Ensure that the C++ Thread and OSThread structures aren't freed before
2774     // we operate.
2775     MutexLocker mu(Threads_lock);
2776 
2777     // Since JDK 5 the java.lang.Thread threadStatus is used to prevent
2778     // re-starting an already started thread, so we should usually find
2779     // that the JavaThread is null. However for a JNI attached thread
2780     // there is a small window between the Thread object being created
2781     // (with its JavaThread set) and the update to its threadStatus, so we
2782     // have to check for this
2783     if (java_lang_Thread::thread(JNIHandles::resolve_non_null(jthread)) != NULL) {
2784       throw_illegal_thread_state = true;
2785     } else {
2786       // We could also check the stillborn flag to see if this thread was already stopped, but
2787       // for historical reasons we let the thread detect that itself when it starts running
2788 
2789       jlong size =
2790              java_lang_Thread::stackSize(JNIHandles::resolve_non_null(jthread));
2791       // Allocate the C++ Thread structure and create the native thread.  The
2792       // stack size retrieved from java is signed, but the constructor takes
2793       // size_t (an unsigned type), so avoid passing negative values which would
2794       // result in really large stacks.
2795       size_t sz = size > 0 ? (size_t) size : 0;
2796       native_thread = new JavaThread(&thread_entry, sz);
2797 
2798       // At this point it may be possible that no osthread was created for the
2799       // JavaThread due to lack of memory. Check for this situation and throw
2800       // an exception if necessary. Eventually we may want to change this so
2801       // that we only grab the lock if the thread was created successfully -
2802       // then we can also do this check and throw the exception in the
2803       // JavaThread constructor.
2804       if (native_thread->osthread() != NULL) {
2805         // Note: the current thread is not being used within "prepare".
2806         native_thread->prepare(jthread);
2807       }
2808     }
2809   }
2810 
2811   if (throw_illegal_thread_state) {
2812     THROW(vmSymbols::java_lang_IllegalThreadStateException());
2813   }
2814 
2815   assert(native_thread != NULL, "Starting null thread?");
2816 
2817   if (native_thread->osthread() == NULL) {
2818     // No one should hold a reference to the 'native_thread'.
2819     delete native_thread;
2820     if (JvmtiExport::should_post_resource_exhausted()) {
2821       JvmtiExport::post_resource_exhausted(
2822         JVMTI_RESOURCE_EXHAUSTED_OOM_ERROR | JVMTI_RESOURCE_EXHAUSTED_THREADS,
2823         os::native_thread_creation_failed_msg());
2824     }
2825     THROW_MSG(vmSymbols::java_lang_OutOfMemoryError(),
2826               os::native_thread_creation_failed_msg());
2827   }
2828 
2829   Thread::start(native_thread);
2830 
2831 JVM_END
2832 
2833 // JVM_Stop is implemented using a VM_Operation, so threads are forced to safepoints
2834 // before the quasi-asynchronous exception is delivered.  This is a little obtrusive,
2835 // but is thought to be reliable and simple. In the case, where the receiver is the
2836 // same thread as the sender, no safepoint is needed.
2837 JVM_ENTRY(void, JVM_StopThread(JNIEnv* env, jobject jthread, jobject throwable))
2838   JVMWrapper("JVM_StopThread");
2839 
2840   oop java_throwable = JNIHandles::resolve(throwable);
2841   if (java_throwable == NULL) {
2842     THROW(vmSymbols::java_lang_NullPointerException());
2843   }
2844   oop java_thread = JNIHandles::resolve_non_null(jthread);
2845   JavaThread* receiver = java_lang_Thread::thread(java_thread);
2846   Events::log_exception(JavaThread::current(),
2847                         "JVM_StopThread thread JavaThread " INTPTR_FORMAT " as oop " INTPTR_FORMAT " [exception " INTPTR_FORMAT "]",
2848                         p2i(receiver), p2i((address)java_thread), p2i(throwable));
2849   // First check if thread is alive
2850   if (receiver != NULL) {
2851     // Check if exception is getting thrown at self (use oop equality, since the
2852     // target object might exit)
2853     if (java_thread == thread->threadObj()) {
2854       THROW_OOP(java_throwable);
2855     } else {
2856       // Enques a VM_Operation to stop all threads and then deliver the exception...
2857       Thread::send_async_exception(java_thread, JNIHandles::resolve(throwable));
2858     }
2859   }
2860   else {
2861     // Either:
2862     // - target thread has not been started before being stopped, or
2863     // - target thread already terminated
2864     // We could read the threadStatus to determine which case it is
2865     // but that is overkill as it doesn't matter. We must set the
2866     // stillborn flag for the first case, and if the thread has already
2867     // exited setting this flag has no affect
2868     java_lang_Thread::set_stillborn(java_thread);
2869   }
2870 JVM_END
2871 
2872 
2873 JVM_ENTRY(jboolean, JVM_IsThreadAlive(JNIEnv* env, jobject jthread))
2874   JVMWrapper("JVM_IsThreadAlive");
2875 
2876   oop thread_oop = JNIHandles::resolve_non_null(jthread);
2877   return java_lang_Thread::is_alive(thread_oop);
2878 JVM_END
2879 
2880 
2881 JVM_ENTRY(void, JVM_SuspendThread(JNIEnv* env, jobject jthread))
2882   JVMWrapper("JVM_SuspendThread");
2883   oop java_thread = JNIHandles::resolve_non_null(jthread);
2884   JavaThread* receiver = java_lang_Thread::thread(java_thread);
2885 
2886   if (receiver != NULL) {
2887     // thread has run and has not exited (still on threads list)
2888 
2889     {
2890       MutexLockerEx ml(receiver->SR_lock(), Mutex::_no_safepoint_check_flag);
2891       if (receiver->is_external_suspend()) {
2892         // Don't allow nested external suspend requests. We can't return
2893         // an error from this interface so just ignore the problem.
2894         return;
2895       }
2896       if (receiver->is_exiting()) { // thread is in the process of exiting
2897         return;
2898       }
2899       receiver->set_external_suspend();
2900     }
2901 
2902     // java_suspend() will catch threads in the process of exiting
2903     // and will ignore them.
2904     receiver->java_suspend();
2905 
2906     // It would be nice to have the following assertion in all the
2907     // time, but it is possible for a racing resume request to have
2908     // resumed this thread right after we suspended it. Temporarily
2909     // enable this assertion if you are chasing a different kind of
2910     // bug.
2911     //
2912     // assert(java_lang_Thread::thread(receiver->threadObj()) == NULL ||
2913     //   receiver->is_being_ext_suspended(), "thread is not suspended");
2914   }
2915 JVM_END
2916 
2917 
2918 JVM_ENTRY(void, JVM_ResumeThread(JNIEnv* env, jobject jthread))
2919   JVMWrapper("JVM_ResumeThread");
2920   // Ensure that the C++ Thread and OSThread structures aren't freed before we operate.
2921   // We need to *always* get the threads lock here, since this operation cannot be allowed during
2922   // a safepoint. The safepoint code relies on suspending a thread to examine its state. If other
2923   // threads randomly resumes threads, then a thread might not be suspended when the safepoint code
2924   // looks at it.
2925   MutexLocker ml(Threads_lock);
2926   JavaThread* thr = java_lang_Thread::thread(JNIHandles::resolve_non_null(jthread));
2927   if (thr != NULL) {
2928     // the thread has run and is not in the process of exiting
2929     thr->java_resume();
2930   }
2931 JVM_END
2932 
2933 
2934 JVM_ENTRY(void, JVM_SetThreadPriority(JNIEnv* env, jobject jthread, jint prio))
2935   JVMWrapper("JVM_SetThreadPriority");
2936   // Ensure that the C++ Thread and OSThread structures aren't freed before we operate
2937   MutexLocker ml(Threads_lock);
2938   oop java_thread = JNIHandles::resolve_non_null(jthread);
2939   java_lang_Thread::set_priority(java_thread, (ThreadPriority)prio);
2940   JavaThread* thr = java_lang_Thread::thread(java_thread);
2941   if (thr != NULL) {                  // Thread not yet started; priority pushed down when it is
2942     Thread::set_priority(thr, (ThreadPriority)prio);
2943   }
2944 JVM_END
2945 
2946 
2947 JVM_ENTRY(void, JVM_Yield(JNIEnv *env, jclass threadClass))
2948   JVMWrapper("JVM_Yield");
2949   if (os::dont_yield()) return;
2950   HOTSPOT_THREAD_YIELD();
2951 
2952   // When ConvertYieldToSleep is off (default), this matches the classic VM use of yield.
2953   // Critical for similar threading behaviour
2954   if (ConvertYieldToSleep) {
2955     os::sleep(thread, MinSleepInterval, false);
2956   } else {
2957     os::naked_yield();
2958   }
2959 JVM_END
2960 
2961 
2962 JVM_ENTRY(void, JVM_Sleep(JNIEnv* env, jclass threadClass, jlong millis))
2963   JVMWrapper("JVM_Sleep");
2964 
2965   if (millis < 0) {
2966     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "timeout value is negative");
2967   }
2968 
2969   if (Thread::is_interrupted (THREAD, true) && !HAS_PENDING_EXCEPTION) {
2970     THROW_MSG(vmSymbols::java_lang_InterruptedException(), "sleep interrupted");
2971   }
2972 
2973   // Save current thread state and restore it at the end of this block.
2974   // And set new thread state to SLEEPING.
2975   JavaThreadSleepState jtss(thread);
2976 
2977   HOTSPOT_THREAD_SLEEP_BEGIN(millis);
2978 
2979   EventThreadSleep event;
2980 
2981   if (millis == 0) {
2982     // When ConvertSleepToYield is on, this matches the classic VM implementation of
2983     // JVM_Sleep. Critical for similar threading behaviour (Win32)
2984     // It appears that in certain GUI contexts, it may be beneficial to do a short sleep
2985     // for SOLARIS
2986     if (ConvertSleepToYield) {
2987       os::naked_yield();
2988     } else {
2989       ThreadState old_state = thread->osthread()->get_state();
2990       thread->osthread()->set_state(SLEEPING);
2991       os::sleep(thread, MinSleepInterval, false);
2992       thread->osthread()->set_state(old_state);
2993     }
2994   } else {
2995     ThreadState old_state = thread->osthread()->get_state();
2996     thread->osthread()->set_state(SLEEPING);
2997     if (os::sleep(thread, millis, true) == OS_INTRPT) {
2998       // An asynchronous exception (e.g., ThreadDeathException) could have been thrown on
2999       // us while we were sleeping. We do not overwrite those.
3000       if (!HAS_PENDING_EXCEPTION) {
3001         if (event.should_commit()) {
3002           event.set_time(millis);
3003           event.commit();
3004         }
3005         HOTSPOT_THREAD_SLEEP_END(1);
3006 
3007         // TODO-FIXME: THROW_MSG returns which means we will not call set_state()
3008         // to properly restore the thread state.  That's likely wrong.
3009         THROW_MSG(vmSymbols::java_lang_InterruptedException(), "sleep interrupted");
3010       }
3011     }
3012     thread->osthread()->set_state(old_state);
3013   }
3014   if (event.should_commit()) {
3015     event.set_time(millis);
3016     event.commit();
3017   }
3018   HOTSPOT_THREAD_SLEEP_END(0);
3019 JVM_END
3020 
3021 JVM_ENTRY(jobject, JVM_CurrentThread(JNIEnv* env, jclass threadClass))
3022   JVMWrapper("JVM_CurrentThread");
3023   oop jthread = thread->threadObj();
3024   assert (thread != NULL, "no current thread!");
3025   return JNIHandles::make_local(env, jthread);
3026 JVM_END
3027 
3028 
3029 JVM_ENTRY(jint, JVM_CountStackFrames(JNIEnv* env, jobject jthread))
3030   JVMWrapper("JVM_CountStackFrames");
3031 
3032   // Ensure that the C++ Thread and OSThread structures aren't freed before we operate
3033   oop java_thread = JNIHandles::resolve_non_null(jthread);
3034   bool throw_illegal_thread_state = false;
3035   int count = 0;
3036 
3037   {
3038     MutexLockerEx ml(thread->threadObj() == java_thread ? NULL : Threads_lock);
3039     // We need to re-resolve the java_thread, since a GC might have happened during the
3040     // acquire of the lock
3041     JavaThread* thr = java_lang_Thread::thread(JNIHandles::resolve_non_null(jthread));
3042 
3043     if (thr == NULL) {
3044       // do nothing
3045     } else if(! thr->is_external_suspend() || ! thr->frame_anchor()->walkable()) {
3046       // Check whether this java thread has been suspended already. If not, throws
3047       // IllegalThreadStateException. We defer to throw that exception until
3048       // Threads_lock is released since loading exception class has to leave VM.
3049       // The correct way to test a thread is actually suspended is
3050       // wait_for_ext_suspend_completion(), but we can't call that while holding
3051       // the Threads_lock. The above tests are sufficient for our purposes
3052       // provided the walkability of the stack is stable - which it isn't
3053       // 100% but close enough for most practical purposes.
3054       throw_illegal_thread_state = true;
3055     } else {
3056       // Count all java activation, i.e., number of vframes
3057       for(vframeStream vfst(thr); !vfst.at_end(); vfst.next()) {
3058         // Native frames are not counted
3059         if (!vfst.method()->is_native()) count++;
3060        }
3061     }
3062   }
3063 
3064   if (throw_illegal_thread_state) {
3065     THROW_MSG_0(vmSymbols::java_lang_IllegalThreadStateException(),
3066                 "this thread is not suspended");
3067   }
3068   return count;
3069 JVM_END
3070 
3071 // Consider: A better way to implement JVM_Interrupt() is to acquire
3072 // Threads_lock to resolve the jthread into a Thread pointer, fetch
3073 // Thread->platformevent, Thread->native_thr, Thread->parker, etc.,
3074 // drop Threads_lock, and the perform the unpark() and thr_kill() operations
3075 // outside the critical section.  Threads_lock is hot so we want to minimize
3076 // the hold-time.  A cleaner interface would be to decompose interrupt into
3077 // two steps.  The 1st phase, performed under Threads_lock, would return
3078 // a closure that'd be invoked after Threads_lock was dropped.
3079 // This tactic is safe as PlatformEvent and Parkers are type-stable (TSM) and
3080 // admit spurious wakeups.
3081 
3082 JVM_ENTRY(void, JVM_Interrupt(JNIEnv* env, jobject jthread))
3083   JVMWrapper("JVM_Interrupt");
3084 
3085   // Ensure that the C++ Thread and OSThread structures aren't freed before we operate
3086   oop java_thread = JNIHandles::resolve_non_null(jthread);
3087   MutexLockerEx ml(thread->threadObj() == java_thread ? NULL : Threads_lock);
3088   // We need to re-resolve the java_thread, since a GC might have happened during the
3089   // acquire of the lock
3090   JavaThread* thr = java_lang_Thread::thread(JNIHandles::resolve_non_null(jthread));
3091   if (thr != NULL) {
3092     Thread::interrupt(thr);
3093   }
3094 JVM_END
3095 
3096 
3097 JVM_QUICK_ENTRY(jboolean, JVM_IsInterrupted(JNIEnv* env, jobject jthread, jboolean clear_interrupted))
3098   JVMWrapper("JVM_IsInterrupted");
3099 
3100   // Ensure that the C++ Thread and OSThread structures aren't freed before we operate
3101   oop java_thread = JNIHandles::resolve_non_null(jthread);
3102   MutexLockerEx ml(thread->threadObj() == java_thread ? NULL : Threads_lock);
3103   // We need to re-resolve the java_thread, since a GC might have happened during the
3104   // acquire of the lock
3105   JavaThread* thr = java_lang_Thread::thread(JNIHandles::resolve_non_null(jthread));
3106   if (thr == NULL) {
3107     return JNI_FALSE;
3108   } else {
3109     return (jboolean) Thread::is_interrupted(thr, clear_interrupted != 0);
3110   }
3111 JVM_END
3112 
3113 
3114 // Return true iff the current thread has locked the object passed in
3115 
3116 JVM_ENTRY(jboolean, JVM_HoldsLock(JNIEnv* env, jclass threadClass, jobject obj))
3117   JVMWrapper("JVM_HoldsLock");
3118   assert(THREAD->is_Java_thread(), "sanity check");
3119   if (obj == NULL) {
3120     THROW_(vmSymbols::java_lang_NullPointerException(), JNI_FALSE);
3121   }
3122   Handle h_obj(THREAD, JNIHandles::resolve(obj));
3123   return ObjectSynchronizer::current_thread_holds_lock((JavaThread*)THREAD, h_obj);
3124 JVM_END
3125 
3126 
3127 JVM_ENTRY(void, JVM_DumpAllStacks(JNIEnv* env, jclass))
3128   JVMWrapper("JVM_DumpAllStacks");
3129   VM_PrintThreads op;
3130   VMThread::execute(&op);
3131   if (JvmtiExport::should_post_data_dump()) {
3132     JvmtiExport::post_data_dump();
3133   }
3134 JVM_END
3135 
3136 JVM_ENTRY(void, JVM_SetNativeThreadName(JNIEnv* env, jobject jthread, jstring name))
3137   JVMWrapper("JVM_SetNativeThreadName");
3138   ResourceMark rm(THREAD);
3139   oop java_thread = JNIHandles::resolve_non_null(jthread);
3140   JavaThread* thr = java_lang_Thread::thread(java_thread);
3141   // Thread naming only supported for the current thread, doesn't work for
3142   // target threads.
3143   if (Thread::current() == thr && !thr->has_attached_via_jni()) {
3144     // we don't set the name of an attached thread to avoid stepping
3145     // on other programs
3146     const char *thread_name = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(name));
3147     os::set_native_thread_name(thread_name);
3148   }
3149 JVM_END
3150 
3151 // java.lang.SecurityManager ///////////////////////////////////////////////////////////////////////
3152 
3153 static bool is_trusted_frame(JavaThread* jthread, vframeStream* vfst) {
3154   assert(jthread->is_Java_thread(), "must be a Java thread");
3155   if (jthread->privileged_stack_top() == NULL) return false;
3156   if (jthread->privileged_stack_top()->frame_id() == vfst->frame_id()) {
3157     oop loader = jthread->privileged_stack_top()->class_loader();
3158     if (loader == NULL) return true;
3159     bool trusted = java_lang_ClassLoader::is_trusted_loader(loader);
3160     if (trusted) return true;
3161   }
3162   return false;
3163 }
3164 
3165 JVM_ENTRY(jclass, JVM_CurrentLoadedClass(JNIEnv *env))
3166   JVMWrapper("JVM_CurrentLoadedClass");
3167   ResourceMark rm(THREAD);
3168 
3169   for (vframeStream vfst(thread); !vfst.at_end(); vfst.next()) {
3170     // if a method in a class in a trusted loader is in a doPrivileged, return NULL
3171     bool trusted = is_trusted_frame(thread, &vfst);
3172     if (trusted) return NULL;
3173 
3174     Method* m = vfst.method();
3175     if (!m->is_native()) {
3176       InstanceKlass* holder = m->method_holder();
3177       oop loader = holder->class_loader();
3178       if (loader != NULL && !java_lang_ClassLoader::is_trusted_loader(loader)) {
3179         return (jclass) JNIHandles::make_local(env, holder->java_mirror());
3180       }
3181     }
3182   }
3183   return NULL;
3184 JVM_END
3185 
3186 
3187 JVM_ENTRY(jobject, JVM_CurrentClassLoader(JNIEnv *env))
3188   JVMWrapper("JVM_CurrentClassLoader");
3189   ResourceMark rm(THREAD);
3190 
3191   for (vframeStream vfst(thread); !vfst.at_end(); vfst.next()) {
3192 
3193     // if a method in a class in a trusted loader is in a doPrivileged, return NULL
3194     bool trusted = is_trusted_frame(thread, &vfst);
3195     if (trusted) return NULL;
3196 
3197     Method* m = vfst.method();
3198     if (!m->is_native()) {
3199       InstanceKlass* holder = m->method_holder();
3200       assert(holder->is_klass(), "just checking");
3201       oop loader = holder->class_loader();
3202       if (loader != NULL && !java_lang_ClassLoader::is_trusted_loader(loader)) {
3203         return JNIHandles::make_local(env, loader);
3204       }
3205     }
3206   }
3207   return NULL;
3208 JVM_END
3209 
3210 
3211 JVM_ENTRY(jobjectArray, JVM_GetClassContext(JNIEnv *env))
3212   JVMWrapper("JVM_GetClassContext");
3213   ResourceMark rm(THREAD);
3214   JvmtiVMObjectAllocEventCollector oam;
3215   vframeStream vfst(thread);
3216 
3217   if (SystemDictionary::reflect_CallerSensitive_klass() != NULL) {
3218     // This must only be called from SecurityManager.getClassContext
3219     Method* m = vfst.method();
3220     if (!(m->method_holder() == SystemDictionary::SecurityManager_klass() &&
3221           m->name()          == vmSymbols::getClassContext_name() &&
3222           m->signature()     == vmSymbols::void_class_array_signature())) {
3223       THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), "JVM_GetClassContext must only be called from SecurityManager.getClassContext");
3224     }
3225   }
3226 
3227   // Collect method holders
3228   GrowableArray<KlassHandle>* klass_array = new GrowableArray<KlassHandle>();
3229   for (; !vfst.at_end(); vfst.security_next()) {
3230     Method* m = vfst.method();
3231     // Native frames are not returned
3232     if (!m->is_ignored_by_security_stack_walk() && !m->is_native()) {
3233       Klass* holder = m->method_holder();
3234       assert(holder->is_klass(), "just checking");
3235       klass_array->append(holder);
3236     }
3237   }
3238 
3239   // Create result array of type [Ljava/lang/Class;
3240   objArrayOop result = oopFactory::new_objArray(SystemDictionary::Class_klass(), klass_array->length(), CHECK_NULL);
3241   // Fill in mirrors corresponding to method holders
3242   for (int i = 0; i < klass_array->length(); i++) {
3243     result->obj_at_put(i, klass_array->at(i)->java_mirror());
3244   }
3245 
3246   return (jobjectArray) JNIHandles::make_local(env, result);
3247 JVM_END
3248 
3249 
3250 JVM_ENTRY(jint, JVM_ClassDepth(JNIEnv *env, jstring name))
3251   JVMWrapper("JVM_ClassDepth");
3252   ResourceMark rm(THREAD);
3253   Handle h_name (THREAD, JNIHandles::resolve_non_null(name));
3254   Handle class_name_str = java_lang_String::internalize_classname(h_name, CHECK_0);
3255 
3256   const char* str = java_lang_String::as_utf8_string(class_name_str());
3257   TempNewSymbol class_name_sym = SymbolTable::probe(str, (int)strlen(str));
3258   if (class_name_sym == NULL) {
3259     return -1;
3260   }
3261 
3262   int depth = 0;
3263 
3264   for(vframeStream vfst(thread); !vfst.at_end(); vfst.next()) {
3265     if (!vfst.method()->is_native()) {
3266       InstanceKlass* holder = vfst.method()->method_holder();
3267       assert(holder->is_klass(), "just checking");
3268       if (holder->name() == class_name_sym) {
3269         return depth;
3270       }
3271       depth++;
3272     }
3273   }
3274   return -1;
3275 JVM_END
3276 
3277 
3278 JVM_ENTRY(jint, JVM_ClassLoaderDepth(JNIEnv *env))
3279   JVMWrapper("JVM_ClassLoaderDepth");
3280   ResourceMark rm(THREAD);
3281   int depth = 0;
3282   for (vframeStream vfst(thread); !vfst.at_end(); vfst.next()) {
3283     // if a method in a class in a trusted loader is in a doPrivileged, return -1
3284     bool trusted = is_trusted_frame(thread, &vfst);
3285     if (trusted) return -1;
3286 
3287     Method* m = vfst.method();
3288     if (!m->is_native()) {
3289       InstanceKlass* holder = m->method_holder();
3290       assert(holder->is_klass(), "just checking");
3291       oop loader = holder->class_loader();
3292       if (loader != NULL && !java_lang_ClassLoader::is_trusted_loader(loader)) {
3293         return depth;
3294       }
3295       depth++;
3296     }
3297   }
3298   return -1;
3299 JVM_END
3300 
3301 
3302 // java.lang.Package ////////////////////////////////////////////////////////////////
3303 
3304 
3305 JVM_ENTRY(jstring, JVM_GetSystemPackage(JNIEnv *env, jstring name))
3306   JVMWrapper("JVM_GetSystemPackage");
3307   ResourceMark rm(THREAD);
3308   JvmtiVMObjectAllocEventCollector oam;
3309   char* str = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(name));
3310   oop result = ClassLoader::get_system_package(str, CHECK_NULL);
3311   return (jstring) JNIHandles::make_local(result);
3312 JVM_END
3313 
3314 
3315 JVM_ENTRY(jobjectArray, JVM_GetSystemPackages(JNIEnv *env))
3316   JVMWrapper("JVM_GetSystemPackages");
3317   JvmtiVMObjectAllocEventCollector oam;
3318   objArrayOop result = ClassLoader::get_system_packages(CHECK_NULL);
3319   return (jobjectArray) JNIHandles::make_local(result);
3320 JVM_END
3321 
3322 
3323 // ObjectInputStream ///////////////////////////////////////////////////////////////
3324 
3325 bool force_verify_field_access(Klass* current_class, Klass* field_class, AccessFlags access, bool classloader_only) {
3326   if (current_class == NULL) {
3327     return true;
3328   }
3329   if ((current_class == field_class) || access.is_public()) {
3330     return true;
3331   }
3332 
3333   if (access.is_protected()) {
3334     // See if current_class is a subclass of field_class
3335     if (current_class->is_subclass_of(field_class)) {
3336       return true;
3337     }
3338   }
3339 
3340   return (!access.is_private() && InstanceKlass::cast(current_class)->is_same_class_package(field_class));
3341 }
3342 
3343 // Return the first non-null class loader up the execution stack, or null
3344 // if only code from the null class loader is on the stack.
3345 
3346 JVM_ENTRY(jobject, JVM_LatestUserDefinedLoader(JNIEnv *env))
3347   for (vframeStream vfst(thread); !vfst.at_end(); vfst.next()) {
3348     vfst.skip_reflection_related_frames(); // Only needed for 1.4 reflection
3349     oop loader = vfst.method()->method_holder()->class_loader();
3350     if (loader != NULL) {
3351       return JNIHandles::make_local(env, loader);
3352     }
3353   }
3354   return NULL;
3355 JVM_END
3356 
3357 
3358 // Array ///////////////////////////////////////////////////////////////////////////////////////////
3359 
3360 
3361 // resolve array handle and check arguments
3362 static inline arrayOop check_array(JNIEnv *env, jobject arr, bool type_array_only, TRAPS) {
3363   if (arr == NULL) {
3364     THROW_0(vmSymbols::java_lang_NullPointerException());
3365   }
3366   oop a = JNIHandles::resolve_non_null(arr);
3367   if (!a->is_array()) {
3368     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Argument is not an array");
3369   } else if (type_array_only && !a->is_typeArray()) {
3370     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Argument is not an array of primitive type");
3371   }
3372   return arrayOop(a);
3373 }
3374 
3375 
3376 JVM_ENTRY(jint, JVM_GetArrayLength(JNIEnv *env, jobject arr))
3377   JVMWrapper("JVM_GetArrayLength");
3378   arrayOop a = check_array(env, arr, false, CHECK_0);
3379   return a->length();
3380 JVM_END
3381 
3382 
3383 JVM_ENTRY(jobject, JVM_GetArrayElement(JNIEnv *env, jobject arr, jint index))
3384   JVMWrapper("JVM_Array_Get");
3385   JvmtiVMObjectAllocEventCollector oam;
3386   arrayOop a = check_array(env, arr, false, CHECK_NULL);
3387   jvalue value;
3388   BasicType type = Reflection::array_get(&value, a, index, CHECK_NULL);
3389   oop box = Reflection::box(&value, type, CHECK_NULL);
3390   return JNIHandles::make_local(env, box);
3391 JVM_END
3392 
3393 
3394 JVM_ENTRY(jvalue, JVM_GetPrimitiveArrayElement(JNIEnv *env, jobject arr, jint index, jint wCode))
3395   JVMWrapper("JVM_GetPrimitiveArrayElement");
3396   jvalue value;
3397   value.i = 0; // to initialize value before getting used in CHECK
3398   arrayOop a = check_array(env, arr, true, CHECK_(value));
3399   assert(a->is_typeArray(), "just checking");
3400   BasicType type = Reflection::array_get(&value, a, index, CHECK_(value));
3401   BasicType wide_type = (BasicType) wCode;
3402   if (type != wide_type) {
3403     Reflection::widen(&value, type, wide_type, CHECK_(value));
3404   }
3405   return value;
3406 JVM_END
3407 
3408 
3409 JVM_ENTRY(void, JVM_SetArrayElement(JNIEnv *env, jobject arr, jint index, jobject val))
3410   JVMWrapper("JVM_SetArrayElement");
3411   arrayOop a = check_array(env, arr, false, CHECK);
3412   oop box = JNIHandles::resolve(val);
3413   jvalue value;
3414   value.i = 0; // to initialize value before getting used in CHECK
3415   BasicType value_type;
3416   if (a->is_objArray()) {
3417     // Make sure we do no unbox e.g. java/lang/Integer instances when storing into an object array
3418     value_type = Reflection::unbox_for_regular_object(box, &value);
3419   } else {
3420     value_type = Reflection::unbox_for_primitive(box, &value, CHECK);
3421   }
3422   Reflection::array_set(&value, a, index, value_type, CHECK);
3423 JVM_END
3424 
3425 
3426 JVM_ENTRY(void, JVM_SetPrimitiveArrayElement(JNIEnv *env, jobject arr, jint index, jvalue v, unsigned char vCode))
3427   JVMWrapper("JVM_SetPrimitiveArrayElement");
3428   arrayOop a = check_array(env, arr, true, CHECK);
3429   assert(a->is_typeArray(), "just checking");
3430   BasicType value_type = (BasicType) vCode;
3431   Reflection::array_set(&v, a, index, value_type, CHECK);
3432 JVM_END
3433 
3434 
3435 JVM_ENTRY(jobject, JVM_NewArray(JNIEnv *env, jclass eltClass, jint length))
3436   JVMWrapper("JVM_NewArray");
3437   JvmtiVMObjectAllocEventCollector oam;
3438   oop element_mirror = JNIHandles::resolve(eltClass);
3439   oop result = Reflection::reflect_new_array(element_mirror, length, CHECK_NULL);
3440   return JNIHandles::make_local(env, result);
3441 JVM_END
3442 
3443 
3444 JVM_ENTRY(jobject, JVM_NewMultiArray(JNIEnv *env, jclass eltClass, jintArray dim))
3445   JVMWrapper("JVM_NewMultiArray");
3446   JvmtiVMObjectAllocEventCollector oam;
3447   arrayOop dim_array = check_array(env, dim, true, CHECK_NULL);
3448   oop element_mirror = JNIHandles::resolve(eltClass);
3449   assert(dim_array->is_typeArray(), "just checking");
3450   oop result = Reflection::reflect_new_multi_array(element_mirror, typeArrayOop(dim_array), CHECK_NULL);
3451   return JNIHandles::make_local(env, result);
3452 JVM_END
3453 
3454 
3455 // Library support ///////////////////////////////////////////////////////////////////////////
3456 
3457 JVM_ENTRY_NO_ENV(void*, JVM_LoadLibrary(const char* name))
3458   //%note jvm_ct
3459   JVMWrapper2("JVM_LoadLibrary (%s)", name);
3460   char ebuf[1024];
3461   void *load_result;
3462   {
3463     ThreadToNativeFromVM ttnfvm(thread);
3464     load_result = os::dll_load(name, ebuf, sizeof ebuf);
3465   }
3466   if (load_result == NULL) {
3467     char msg[1024];
3468     jio_snprintf(msg, sizeof msg, "%s: %s", name, ebuf);
3469     // Since 'ebuf' may contain a string encoded using
3470     // platform encoding scheme, we need to pass
3471     // Exceptions::unsafe_to_utf8 to the new_exception method
3472     // as the last argument. See bug 6367357.
3473     Handle h_exception =
3474       Exceptions::new_exception(thread,
3475                                 vmSymbols::java_lang_UnsatisfiedLinkError(),
3476                                 msg, Exceptions::unsafe_to_utf8);
3477 
3478     THROW_HANDLE_0(h_exception);
3479   }
3480   return load_result;
3481 JVM_END
3482 
3483 
3484 JVM_LEAF(void, JVM_UnloadLibrary(void* handle))
3485   JVMWrapper("JVM_UnloadLibrary");
3486   os::dll_unload(handle);
3487 JVM_END
3488 
3489 
3490 JVM_LEAF(void*, JVM_FindLibraryEntry(void* handle, const char* name))
3491   JVMWrapper2("JVM_FindLibraryEntry (%s)", name);
3492   return os::dll_lookup(handle, name);
3493 JVM_END
3494 
3495 
3496 // JNI version ///////////////////////////////////////////////////////////////////////////////
3497 
3498 JVM_LEAF(jboolean, JVM_IsSupportedJNIVersion(jint version))
3499   JVMWrapper2("JVM_IsSupportedJNIVersion (%d)", version);
3500   return Threads::is_supported_jni_version_including_1_1(version);
3501 JVM_END
3502 
3503 
3504 // String support ///////////////////////////////////////////////////////////////////////////
3505 
3506 JVM_ENTRY(jstring, JVM_InternString(JNIEnv *env, jstring str))
3507   JVMWrapper("JVM_InternString");
3508   JvmtiVMObjectAllocEventCollector oam;
3509   if (str == NULL) return NULL;
3510   oop string = JNIHandles::resolve_non_null(str);
3511   oop result = StringTable::intern(string, CHECK_NULL);
3512   return (jstring) JNIHandles::make_local(env, result);
3513 JVM_END
3514 
3515 
3516 // Raw monitor support //////////////////////////////////////////////////////////////////////
3517 
3518 // The lock routine below calls lock_without_safepoint_check in order to get a raw lock
3519 // without interfering with the safepoint mechanism. The routines are not JVM_LEAF because
3520 // they might be called by non-java threads. The JVM_LEAF installs a NoHandleMark check
3521 // that only works with java threads.
3522 
3523 
3524 JNIEXPORT void* JNICALL JVM_RawMonitorCreate(void) {
3525   VM_Exit::block_if_vm_exited();
3526   JVMWrapper("JVM_RawMonitorCreate");
3527   return new Mutex(Mutex::native, "JVM_RawMonitorCreate");
3528 }
3529 
3530 
3531 JNIEXPORT void JNICALL  JVM_RawMonitorDestroy(void *mon) {
3532   VM_Exit::block_if_vm_exited();
3533   JVMWrapper("JVM_RawMonitorDestroy");
3534   delete ((Mutex*) mon);
3535 }
3536 
3537 
3538 JNIEXPORT jint JNICALL JVM_RawMonitorEnter(void *mon) {
3539   VM_Exit::block_if_vm_exited();
3540   JVMWrapper("JVM_RawMonitorEnter");
3541   ((Mutex*) mon)->jvm_raw_lock();
3542   return 0;
3543 }
3544 
3545 
3546 JNIEXPORT void JNICALL JVM_RawMonitorExit(void *mon) {
3547   VM_Exit::block_if_vm_exited();
3548   JVMWrapper("JVM_RawMonitorExit");
3549   ((Mutex*) mon)->jvm_raw_unlock();
3550 }
3551 
3552 
3553 // Shared JNI/JVM entry points //////////////////////////////////////////////////////////////
3554 
3555 jclass find_class_from_class_loader(JNIEnv* env, Symbol* name, jboolean init,
3556                                     Handle loader, Handle protection_domain,
3557                                     jboolean throwError, TRAPS) {
3558   // Security Note:
3559   //   The Java level wrapper will perform the necessary security check allowing
3560   //   us to pass the NULL as the initiating class loader.  The VM is responsible for
3561   //   the checkPackageAccess relative to the initiating class loader via the
3562   //   protection_domain. The protection_domain is passed as NULL by the java code
3563   //   if there is no security manager in 3-arg Class.forName().
3564   Klass* klass = SystemDictionary::resolve_or_fail(name, loader, protection_domain, throwError != 0, CHECK_NULL);
3565 
3566   KlassHandle klass_handle(THREAD, klass);
3567   // Check if we should initialize the class
3568   if (init && klass_handle->oop_is_instance()) {
3569     klass_handle->initialize(CHECK_NULL);
3570   }
3571   return (jclass) JNIHandles::make_local(env, klass_handle->java_mirror());
3572 }
3573 
3574 
3575 // Method ///////////////////////////////////////////////////////////////////////////////////////////
3576 
3577 JVM_ENTRY(jobject, JVM_InvokeMethod(JNIEnv *env, jobject method, jobject obj, jobjectArray args0))
3578   JVMWrapper("JVM_InvokeMethod");
3579   Handle method_handle;
3580   if (thread->stack_available((address) &method_handle) >= JVMInvokeMethodSlack) {
3581     method_handle = Handle(THREAD, JNIHandles::resolve(method));
3582     Handle receiver(THREAD, JNIHandles::resolve(obj));
3583     objArrayHandle args(THREAD, objArrayOop(JNIHandles::resolve(args0)));
3584     oop result = Reflection::invoke_method(method_handle(), receiver, args, CHECK_NULL);
3585     jobject res = JNIHandles::make_local(env, result);
3586     if (JvmtiExport::should_post_vm_object_alloc()) {
3587       oop ret_type = java_lang_reflect_Method::return_type(method_handle());
3588       assert(ret_type != NULL, "sanity check: ret_type oop must not be NULL!");
3589       if (java_lang_Class::is_primitive(ret_type)) {
3590         // Only for primitive type vm allocates memory for java object.
3591         // See box() method.
3592         JvmtiExport::post_vm_object_alloc(JavaThread::current(), result);
3593       }
3594     }
3595     return res;
3596   } else {
3597     THROW_0(vmSymbols::java_lang_StackOverflowError());
3598   }
3599 JVM_END
3600 
3601 
3602 JVM_ENTRY(jobject, JVM_NewInstanceFromConstructor(JNIEnv *env, jobject c, jobjectArray args0))
3603   JVMWrapper("JVM_NewInstanceFromConstructor");
3604   oop constructor_mirror = JNIHandles::resolve(c);
3605   objArrayHandle args(THREAD, objArrayOop(JNIHandles::resolve(args0)));
3606   oop result = Reflection::invoke_constructor(constructor_mirror, args, CHECK_NULL);
3607   jobject res = JNIHandles::make_local(env, result);
3608   if (JvmtiExport::should_post_vm_object_alloc()) {
3609     JvmtiExport::post_vm_object_alloc(JavaThread::current(), result);
3610   }
3611   return res;
3612 JVM_END
3613 
3614 // Atomic ///////////////////////////////////////////////////////////////////////////////////////////
3615 
3616 JVM_LEAF(jboolean, JVM_SupportsCX8())
3617   JVMWrapper("JVM_SupportsCX8");
3618   return VM_Version::supports_cx8();
3619 JVM_END
3620 
3621 // Returns an array of all live Thread objects (VM internal JavaThreads,
3622 // jvmti agent threads, and JNI attaching threads  are skipped)
3623 // See CR 6404306 regarding JNI attaching threads
3624 JVM_ENTRY(jobjectArray, JVM_GetAllThreads(JNIEnv *env, jclass dummy))
3625   ResourceMark rm(THREAD);
3626   ThreadsListEnumerator tle(THREAD, false, false);
3627   JvmtiVMObjectAllocEventCollector oam;
3628 
3629   int num_threads = tle.num_threads();
3630   objArrayOop r = oopFactory::new_objArray(SystemDictionary::Thread_klass(), num_threads, CHECK_NULL);
3631   objArrayHandle threads_ah(THREAD, r);
3632 
3633   for (int i = 0; i < num_threads; i++) {
3634     Handle h = tle.get_threadObj(i);
3635     threads_ah->obj_at_put(i, h());
3636   }
3637 
3638   return (jobjectArray) JNIHandles::make_local(env, threads_ah());
3639 JVM_END
3640 
3641 
3642 // Support for java.lang.Thread.getStackTrace() and getAllStackTraces() methods
3643 // Return StackTraceElement[][], each element is the stack trace of a thread in
3644 // the corresponding entry in the given threads array
3645 JVM_ENTRY(jobjectArray, JVM_DumpThreads(JNIEnv *env, jclass threadClass, jobjectArray threads))
3646   JVMWrapper("JVM_DumpThreads");
3647   JvmtiVMObjectAllocEventCollector oam;
3648 
3649   // Check if threads is null
3650   if (threads == NULL) {
3651     THROW_(vmSymbols::java_lang_NullPointerException(), 0);
3652   }
3653 
3654   objArrayOop a = objArrayOop(JNIHandles::resolve_non_null(threads));
3655   objArrayHandle ah(THREAD, a);
3656   int num_threads = ah->length();
3657   // check if threads is non-empty array
3658   if (num_threads == 0) {
3659     THROW_(vmSymbols::java_lang_IllegalArgumentException(), 0);
3660   }
3661 
3662   // check if threads is not an array of objects of Thread class
3663   Klass* k = ObjArrayKlass::cast(ah->klass())->element_klass();
3664   if (k != SystemDictionary::Thread_klass()) {
3665     THROW_(vmSymbols::java_lang_IllegalArgumentException(), 0);
3666   }
3667 
3668   ResourceMark rm(THREAD);
3669 
3670   GrowableArray<instanceHandle>* thread_handle_array = new GrowableArray<instanceHandle>(num_threads);
3671   for (int i = 0; i < num_threads; i++) {
3672     oop thread_obj = ah->obj_at(i);
3673     instanceHandle h(THREAD, (instanceOop) thread_obj);
3674     thread_handle_array->append(h);
3675   }
3676 
3677   Handle stacktraces = ThreadService::dump_stack_traces(thread_handle_array, num_threads, CHECK_NULL);
3678   return (jobjectArray)JNIHandles::make_local(env, stacktraces());
3679 
3680 JVM_END
3681 
3682 // JVM monitoring and management support
3683 JVM_ENTRY_NO_ENV(void*, JVM_GetManagement(jint version))
3684   return Management::get_jmm_interface(version);
3685 JVM_END
3686 
3687 // com.sun.tools.attach.VirtualMachine agent properties support
3688 //
3689 // Initialize the agent properties with the properties maintained in the VM
3690 JVM_ENTRY(jobject, JVM_InitAgentProperties(JNIEnv *env, jobject properties))
3691   JVMWrapper("JVM_InitAgentProperties");
3692   ResourceMark rm;
3693 
3694   Handle props(THREAD, JNIHandles::resolve_non_null(properties));
3695 
3696   PUTPROP(props, "sun.java.command", Arguments::java_command());
3697   PUTPROP(props, "sun.jvm.flags", Arguments::jvm_flags());
3698   PUTPROP(props, "sun.jvm.args", Arguments::jvm_args());
3699   return properties;
3700 JVM_END
3701 
3702 JVM_ENTRY(jobjectArray, JVM_GetEnclosingMethodInfo(JNIEnv *env, jclass ofClass))
3703 {
3704   JVMWrapper("JVM_GetEnclosingMethodInfo");
3705   JvmtiVMObjectAllocEventCollector oam;
3706 
3707   if (ofClass == NULL) {
3708     return NULL;
3709   }
3710   Handle mirror(THREAD, JNIHandles::resolve_non_null(ofClass));
3711   // Special handling for primitive objects
3712   if (java_lang_Class::is_primitive(mirror())) {
3713     return NULL;
3714   }
3715   Klass* k = java_lang_Class::as_Klass(mirror());
3716   if (!k->oop_is_instance()) {
3717     return NULL;
3718   }
3719   instanceKlassHandle ik_h(THREAD, k);
3720   int encl_method_class_idx = ik_h->enclosing_method_class_index();
3721   if (encl_method_class_idx == 0) {
3722     return NULL;
3723   }
3724   objArrayOop dest_o = oopFactory::new_objArray(SystemDictionary::Object_klass(), 3, CHECK_NULL);
3725   objArrayHandle dest(THREAD, dest_o);
3726   Klass* enc_k = ik_h->constants()->klass_at(encl_method_class_idx, CHECK_NULL);
3727   dest->obj_at_put(0, enc_k->java_mirror());
3728   int encl_method_method_idx = ik_h->enclosing_method_method_index();
3729   if (encl_method_method_idx != 0) {
3730     Symbol* sym = ik_h->constants()->symbol_at(
3731                         extract_low_short_from_int(
3732                           ik_h->constants()->name_and_type_at(encl_method_method_idx)));
3733     Handle str = java_lang_String::create_from_symbol(sym, CHECK_NULL);
3734     dest->obj_at_put(1, str());
3735     sym = ik_h->constants()->symbol_at(
3736               extract_high_short_from_int(
3737                 ik_h->constants()->name_and_type_at(encl_method_method_idx)));
3738     str = java_lang_String::create_from_symbol(sym, CHECK_NULL);
3739     dest->obj_at_put(2, str());
3740   }
3741   return (jobjectArray) JNIHandles::make_local(dest());
3742 }
3743 JVM_END
3744 
3745 JVM_ENTRY(void, JVM_GetVersionInfo(JNIEnv* env, jvm_version_info* info, size_t info_size))
3746 {
3747   memset(info, 0, info_size);
3748 
3749   info->jvm_version = Abstract_VM_Version::jvm_version();
3750   info->update_version = 0;          /* 0 in HotSpot Express VM */
3751   info->special_update_version = 0;  /* 0 in HotSpot Express VM */
3752 
3753   // when we add a new capability in the jvm_version_info struct, we should also
3754   // consider to expose this new capability in the sun.rt.jvmCapabilities jvmstat
3755   // counter defined in runtimeService.cpp.
3756   info->is_attachable = AttachListener::is_attach_supported();
3757 }
3758 JVM_END