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