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