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