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