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