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