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