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