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