1 /*
   2  * Copyright (c) 1997, 2020, 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 "classfile/classLoader.hpp"
  27 #include "classfile/classLoaderData.inline.hpp"
  28 #include "classfile/classLoaderExt.hpp"
  29 #include "classfile/javaAssertions.hpp"
  30 #include "classfile/javaClasses.hpp"
  31 #include "classfile/symbolTable.hpp"
  32 #include "classfile/systemDictionary.hpp"
  33 #if INCLUDE_CDS
  34 #include "classfile/sharedClassUtil.hpp"
  35 #include "classfile/systemDictionaryShared.hpp"
  36 #endif
  37 #include "classfile/vmSymbols.hpp"
  38 #include "gc_interface/collectedHeap.inline.hpp"
  39 #include "interpreter/bytecode.hpp"
  40 #include "jfr/jfrEvents.hpp"
  41 #include "memory/oopFactory.hpp"
  42 #include "memory/referenceType.hpp"
  43 #include "memory/universe.inline.hpp"
  44 #include "oops/fieldStreams.hpp"
  45 #include "oops/instanceKlass.hpp"
  46 #include "oops/objArrayKlass.hpp"
  47 #include "oops/method.hpp"
  48 #include "prims/jvm.h"
  49 #include "prims/jvm_misc.hpp"
  50 #include "prims/jvmtiExport.hpp"
  51 #include "prims/jvmtiThreadState.hpp"
  52 #include "prims/nativeLookup.hpp"
  53 #include "prims/privilegedStack.hpp"
  54 #include "runtime/arguments.hpp"
  55 #include "runtime/dtraceJSDT.hpp"
  56 #include "runtime/handles.inline.hpp"
  57 #include "runtime/init.hpp"
  58 #include "runtime/interfaceSupport.hpp"
  59 #include "runtime/java.hpp"
  60 #include "runtime/javaCalls.hpp"
  61 #include "runtime/jfieldIDWorkaround.hpp"
  62 #include "runtime/orderAccess.inline.hpp"
  63 #include "runtime/os.hpp"
  64 #include "runtime/perfData.hpp"
  65 #include "runtime/reflection.hpp"
  66 #include "runtime/vframe.hpp"
  67 #include "runtime/vm_operations.hpp"
  68 #include "services/attachListener.hpp"
  69 #include "services/management.hpp"
  70 #include "services/threadService.hpp"
  71 #include "utilities/copy.hpp"
  72 #include "utilities/defaultStream.hpp"
  73 #include "utilities/dtrace.hpp"
  74 #include "utilities/events.hpp"
  75 #include "utilities/histogram.hpp"
  76 #include "utilities/top.hpp"
  77 #include "utilities/utf8.hpp"
  78 #ifdef TARGET_OS_FAMILY_linux
  79 # include "jvm_linux.h"
  80 #endif
  81 #ifdef TARGET_OS_FAMILY_solaris
  82 # include "jvm_solaris.h"
  83 #endif
  84 #ifdef TARGET_OS_FAMILY_windows
  85 # include "jvm_windows.h"
  86 #endif
  87 #ifdef TARGET_OS_FAMILY_aix
  88 # include "jvm_aix.h"
  89 #endif
  90 #ifdef TARGET_OS_FAMILY_bsd
  91 # include "jvm_bsd.h"
  92 #endif
  93 
  94 #if INCLUDE_ALL_GCS
  95 #include "gc_implementation/g1/g1SATBCardTableModRefBS.hpp"
  96 #endif // INCLUDE_ALL_GCS
  97 
  98 #include <errno.h>
  99 #include <jfr/recorder/jfrRecorder.hpp>
 100 
 101 #ifndef USDT2
 102 HS_DTRACE_PROBE_DECL1(hotspot, thread__sleep__begin, long long);
 103 HS_DTRACE_PROBE_DECL1(hotspot, thread__sleep__end, int);
 104 HS_DTRACE_PROBE_DECL0(hotspot, thread__yield);
 105 #endif /* !USDT2 */
 106 
 107 /*
 108   NOTE about use of any ctor or function call that can trigger a safepoint/GC:
 109   such ctors and calls MUST NOT come between an oop declaration/init and its
 110   usage because if objects are move this may cause various memory stomps, bus
 111   errors and segfaults. Here is a cookbook for causing so called "naked oop
 112   failures":
 113 
 114       JVM_ENTRY(jobjectArray, JVM_GetClassDeclaredFields<etc> {
 115           JVMWrapper("JVM_GetClassDeclaredFields");
 116 
 117           // Object address to be held directly in mirror & not visible to GC
 118           oop mirror = JNIHandles::resolve_non_null(ofClass);
 119 
 120           // If this ctor can hit a safepoint, moving objects around, then
 121           ComplexConstructor foo;
 122 
 123           // Boom! mirror may point to JUNK instead of the intended object
 124           (some dereference of mirror)
 125 
 126           // Here's another call that may block for GC, making mirror stale
 127           MutexLocker ml(some_lock);
 128 
 129           // And here's an initializer that can result in a stale oop
 130           // all in one step.
 131           oop o = call_that_can_throw_exception(TRAPS);
 132 
 133 
 134   The solution is to keep the oop declaration BELOW the ctor or function
 135   call that might cause a GC, do another resolve to reassign the oop, or
 136   consider use of a Handle instead of an oop so there is immunity from object
 137   motion. But note that the "QUICK" entries below do not have a handlemark
 138   and thus can only support use of handles passed in.
 139 */
 140 
 141 static void trace_class_resolution_impl(Klass* to_class, TRAPS) {
 142   ResourceMark rm;
 143   int line_number = -1;
 144   const char * source_file = NULL;
 145   const char * trace = "explicit";
 146   InstanceKlass* caller = NULL;
 147   JavaThread* jthread = JavaThread::current();
 148   if (jthread->has_last_Java_frame()) {
 149     vframeStream vfst(jthread);
 150 
 151     // scan up the stack skipping ClassLoader, AccessController and PrivilegedAction frames
 152     TempNewSymbol access_controller = SymbolTable::new_symbol("java/security/AccessController", CHECK);
 153     Klass* access_controller_klass = SystemDictionary::resolve_or_fail(access_controller, false, CHECK);
 154     TempNewSymbol privileged_action = SymbolTable::new_symbol("java/security/PrivilegedAction", CHECK);
 155     Klass* privileged_action_klass = SystemDictionary::resolve_or_fail(privileged_action, false, CHECK);
 156 
 157     Method* last_caller = NULL;
 158 
 159     while (!vfst.at_end()) {
 160       Method* m = vfst.method();
 161       if (!vfst.method()->method_holder()->is_subclass_of(SystemDictionary::ClassLoader_klass())&&
 162           !vfst.method()->method_holder()->is_subclass_of(access_controller_klass) &&
 163           !vfst.method()->method_holder()->is_subclass_of(privileged_action_klass)) {
 164         break;
 165       }
 166       last_caller = m;
 167       vfst.next();
 168     }
 169     // if this is called from Class.forName0 and that is called from Class.forName,
 170     // then print the caller of Class.forName.  If this is Class.loadClass, then print
 171     // that caller, otherwise keep quiet since this should be picked up elsewhere.
 172     bool found_it = false;
 173     if (!vfst.at_end() &&
 174         vfst.method()->method_holder()->name() == vmSymbols::java_lang_Class() &&
 175         vfst.method()->name() == vmSymbols::forName0_name()) {
 176       vfst.next();
 177       if (!vfst.at_end() &&
 178           vfst.method()->method_holder()->name() == vmSymbols::java_lang_Class() &&
 179           vfst.method()->name() == vmSymbols::forName_name()) {
 180         vfst.next();
 181         found_it = true;
 182       }
 183     } else if (last_caller != NULL &&
 184                last_caller->method_holder()->name() ==
 185                vmSymbols::java_lang_ClassLoader() &&
 186                (last_caller->name() == vmSymbols::loadClassInternal_name() ||
 187                 last_caller->name() == vmSymbols::loadClass_name())) {
 188       found_it = true;
 189     } else if (!vfst.at_end()) {
 190       if (vfst.method()->is_native()) {
 191         // JNI call
 192         found_it = true;
 193       }
 194     }
 195     if (found_it && !vfst.at_end()) {
 196       // found the caller
 197       caller = vfst.method()->method_holder();
 198       line_number = vfst.method()->line_number_from_bci(vfst.bci());
 199       if (line_number == -1) {
 200         // show method name if it's a native method
 201         trace = vfst.method()->name_and_sig_as_C_string();
 202       }
 203       Symbol* s = caller->source_file_name();
 204       if (s != NULL) {
 205         source_file = s->as_C_string();
 206       }
 207     }
 208   }
 209   if (caller != NULL) {
 210     if (to_class != caller) {
 211       const char * from = caller->external_name();
 212       const char * to = to_class->external_name();
 213       // print in a single call to reduce interleaving between threads
 214       if (source_file != NULL) {
 215         tty->print("RESOLVE %s %s %s:%d (%s)\n", from, to, source_file, line_number, trace);
 216       } else {
 217         tty->print("RESOLVE %s %s (%s)\n", from, to, trace);
 218       }
 219     }
 220   }
 221 }
 222 
 223 void trace_class_resolution(Klass* to_class) {
 224   EXCEPTION_MARK;
 225   trace_class_resolution_impl(to_class, THREAD);
 226   if (HAS_PENDING_EXCEPTION) {
 227     CLEAR_PENDING_EXCEPTION;
 228   }
 229 }
 230 
 231 // Wrapper to trace JVM functions
 232 
 233 #ifdef ASSERT
 234   class JVMTraceWrapper : public StackObj {
 235    public:
 236     JVMTraceWrapper(const char* format, ...) ATTRIBUTE_PRINTF(2, 3) {
 237       if (TraceJVMCalls) {
 238         va_list ap;
 239         va_start(ap, format);
 240         tty->print("JVM ");
 241         tty->vprint_cr(format, ap);
 242         va_end(ap);
 243       }
 244     }
 245   };
 246 
 247   Histogram* JVMHistogram;
 248   volatile jint JVMHistogram_lock = 0;
 249 
 250   class JVMHistogramElement : public HistogramElement {
 251     public:
 252      JVMHistogramElement(const char* name);
 253   };
 254 
 255   JVMHistogramElement::JVMHistogramElement(const char* elementName) {
 256     _name = elementName;
 257     uintx count = 0;
 258 
 259     while (Atomic::cmpxchg(1, &JVMHistogram_lock, 0) != 0) {
 260       while (OrderAccess::load_acquire(&JVMHistogram_lock) != 0) {
 261         count +=1;
 262         if ( (WarnOnStalledSpinLock > 0)
 263           && (count % WarnOnStalledSpinLock == 0)) {
 264           warning("JVMHistogram_lock seems to be stalled");
 265         }
 266       }
 267      }
 268 
 269     if(JVMHistogram == NULL)
 270       JVMHistogram = new Histogram("JVM Call Counts",100);
 271 
 272     JVMHistogram->add_element(this);
 273     Atomic::dec(&JVMHistogram_lock);
 274   }
 275 
 276   #define JVMCountWrapper(arg) \
 277       static JVMHistogramElement* e = new JVMHistogramElement(arg); \
 278       if (e != NULL) e->increment_count();  // Due to bug in VC++, we need a NULL check here eventhough it should never happen!
 279 
 280   #define JVMWrapper(arg1)                    JVMCountWrapper(arg1); JVMTraceWrapper(arg1)
 281   #define JVMWrapper2(arg1, arg2)             JVMCountWrapper(arg1); JVMTraceWrapper(arg1, arg2)
 282   #define JVMWrapper3(arg1, arg2, arg3)       JVMCountWrapper(arg1); JVMTraceWrapper(arg1, arg2, arg3)
 283   #define JVMWrapper4(arg1, arg2, arg3, arg4) JVMCountWrapper(arg1); JVMTraceWrapper(arg1, arg2, arg3, arg4)
 284 #else
 285   #define JVMWrapper(arg1)
 286   #define JVMWrapper2(arg1, arg2)
 287   #define JVMWrapper3(arg1, arg2, arg3)
 288   #define JVMWrapper4(arg1, arg2, arg3, arg4)
 289 #endif
 290 
 291 
 292 // Interface version /////////////////////////////////////////////////////////////////////
 293 
 294 
 295 JVM_LEAF(jint, JVM_GetInterfaceVersion())
 296   return JVM_INTERFACE_VERSION;
 297 JVM_END
 298 
 299 
 300 // java.lang.System //////////////////////////////////////////////////////////////////////
 301 
 302 
 303 JVM_LEAF(jlong, JVM_CurrentTimeMillis(JNIEnv *env, jclass ignored))
 304   JVMWrapper("JVM_CurrentTimeMillis");
 305   return os::javaTimeMillis();
 306 JVM_END
 307 
 308 JVM_LEAF(jlong, JVM_NanoTime(JNIEnv *env, jclass ignored))
 309   JVMWrapper("JVM_NanoTime");
 310   return os::javaTimeNanos();
 311 JVM_END
 312 
 313 
 314 JVM_ENTRY(void, JVM_ArrayCopy(JNIEnv *env, jclass ignored, jobject src, jint src_pos,
 315                                jobject dst, jint dst_pos, jint length))
 316   JVMWrapper("JVM_ArrayCopy");
 317   // Check if we have null pointers
 318   if (src == NULL || dst == NULL) {
 319     THROW(vmSymbols::java_lang_NullPointerException());
 320   }
 321   arrayOop s = arrayOop(JNIHandles::resolve_non_null(src));
 322   arrayOop d = arrayOop(JNIHandles::resolve_non_null(dst));
 323   assert(s->is_oop(), "JVM_ArrayCopy: src not an oop");
 324   assert(d->is_oop(), "JVM_ArrayCopy: dst not an oop");
 325   // Do copy
 326   s->klass()->copy_array(s, src_pos, d, dst_pos, length, thread);
 327 JVM_END
 328 
 329 
 330 static void set_property(Handle props, const char* key, const char* value, TRAPS) {
 331   JavaValue r(T_OBJECT);
 332   // public synchronized Object put(Object key, Object value);
 333   HandleMark hm(THREAD);
 334   Handle key_str    = java_lang_String::create_from_platform_dependent_str(key, CHECK);
 335   Handle value_str  = java_lang_String::create_from_platform_dependent_str((value != NULL ? value : ""), CHECK);
 336   JavaCalls::call_virtual(&r,
 337                           props,
 338                           KlassHandle(THREAD, SystemDictionary::Properties_klass()),
 339                           vmSymbols::put_name(),
 340                           vmSymbols::object_object_object_signature(),
 341                           key_str,
 342                           value_str,
 343                           THREAD);
 344 }
 345 
 346 
 347 #define PUTPROP(props, name, value) set_property((props), (name), (value), CHECK_(properties));
 348 
 349 
 350 JVM_ENTRY(jobject, JVM_InitProperties(JNIEnv *env, jobject properties))
 351   JVMWrapper("JVM_InitProperties");
 352   ResourceMark rm;
 353 
 354   Handle props(THREAD, JNIHandles::resolve_non_null(properties));
 355 
 356   // System property list includes both user set via -D option and
 357   // jvm system specific properties.
 358   for (SystemProperty* p = Arguments::system_properties(); p != NULL; p = p->next()) {
 359     PUTPROP(props, p->key(), p->value());
 360   }
 361 
 362   // Convert the -XX:MaxDirectMemorySize= command line flag
 363   // to the sun.nio.MaxDirectMemorySize property.
 364   // Do this after setting user properties to prevent people
 365   // from setting the value with a -D option, as requested.
 366   {
 367     if (FLAG_IS_DEFAULT(MaxDirectMemorySize)) {
 368       PUTPROP(props, "sun.nio.MaxDirectMemorySize", "-1");
 369     } else {
 370       char as_chars[256];
 371       jio_snprintf(as_chars, sizeof(as_chars), UINTX_FORMAT, MaxDirectMemorySize);
 372       PUTPROP(props, "sun.nio.MaxDirectMemorySize", as_chars);
 373     }
 374   }
 375 
 376   // JVM monitoring and management support
 377   // Add the sun.management.compiler property for the compiler's name
 378   {
 379 #undef CSIZE
 380 #if defined(_LP64) || defined(_WIN64)
 381   #define CSIZE "64-Bit "
 382 #else
 383   #define CSIZE
 384 #endif // 64bit
 385 
 386 #ifdef TIERED
 387     const char* compiler_name = "HotSpot " CSIZE "Tiered Compilers";
 388 #else
 389 #if defined(COMPILER1)
 390     const char* compiler_name = "HotSpot " CSIZE "Client Compiler";
 391 #elif defined(COMPILER2)
 392     const char* compiler_name = "HotSpot " CSIZE "Server Compiler";
 393 #else
 394     const char* compiler_name = "";
 395 #endif // compilers
 396 #endif // TIERED
 397 
 398     if (*compiler_name != '\0' &&
 399         (Arguments::mode() != Arguments::_int)) {
 400       PUTPROP(props, "sun.management.compiler", compiler_name);
 401     }
 402   }
 403 
 404   const char* enableSharedLookupCache = "false";
 405 #if INCLUDE_CDS
 406   if (ClassLoaderExt::is_lookup_cache_enabled()) {
 407     enableSharedLookupCache = "true";
 408   }
 409 #endif
 410   PUTPROP(props, "sun.cds.enableSharedLookupCache", enableSharedLookupCache);
 411 
 412   return properties;
 413 JVM_END
 414 
 415 
 416 /*
 417  * Return the temporary directory that the VM uses for the attach
 418  * and perf data files.
 419  *
 420  * It is important that this directory is well-known and the
 421  * same for all VM instances. It cannot be affected by configuration
 422  * variables such as java.io.tmpdir.
 423  */
 424 JVM_ENTRY(jstring, JVM_GetTemporaryDirectory(JNIEnv *env))
 425   JVMWrapper("JVM_GetTemporaryDirectory");
 426   HandleMark hm(THREAD);
 427   const char* temp_dir = os::get_temp_directory();
 428   Handle h = java_lang_String::create_from_platform_dependent_str(temp_dir, CHECK_NULL);
 429   return (jstring) JNIHandles::make_local(env, h());
 430 JVM_END
 431 
 432 
 433 // java.lang.Runtime /////////////////////////////////////////////////////////////////////////
 434 
 435 extern volatile jint vm_created;
 436 
 437 JVM_ENTRY_NO_ENV(void, JVM_Exit(jint code))
 438   if (vm_created != 0 && (code == 0)) {
 439     // The VM is about to exit. We call back into Java to check whether finalizers should be run
 440     Universe::run_finalizers_on_exit();
 441   }
 442   before_exit(thread);
 443   vm_exit(code);
 444 JVM_END
 445 
 446 
 447 JVM_ENTRY_NO_ENV(void, JVM_BeforeHalt())
 448   JVMWrapper("JVM_BeforeHalt");
 449   EventShutdown event;
 450   if (event.should_commit()) {
 451     event.set_reason("Shutdown requested from Java");
 452     event.commit();
 453   }
 454 JVM_END
 455 
 456 
 457 JVM_ENTRY_NO_ENV(void, JVM_Halt(jint code))
 458   before_exit(thread);
 459   vm_exit(code);
 460 JVM_END
 461 
 462 
 463 JVM_LEAF(void, JVM_OnExit(void (*func)(void)))
 464   register_on_exit_function(func);
 465 JVM_END
 466 
 467 
 468 JVM_ENTRY_NO_ENV(void, JVM_GC(void))
 469   JVMWrapper("JVM_GC");
 470   if (!DisableExplicitGC) {
 471     Universe::heap()->collect(GCCause::_java_lang_system_gc);
 472   }
 473 JVM_END
 474 
 475 
 476 JVM_LEAF(jlong, JVM_MaxObjectInspectionAge(void))
 477   JVMWrapper("JVM_MaxObjectInspectionAge");
 478   return Universe::heap()->millis_since_last_gc();
 479 JVM_END
 480 
 481 
 482 JVM_LEAF(void, JVM_TraceInstructions(jboolean on))
 483   if (PrintJVMWarnings) warning("JVM_TraceInstructions not supported");
 484 JVM_END
 485 
 486 
 487 JVM_LEAF(void, JVM_TraceMethodCalls(jboolean on))
 488   if (PrintJVMWarnings) warning("JVM_TraceMethodCalls not supported");
 489 JVM_END
 490 
 491 static inline jlong convert_size_t_to_jlong(size_t val) {
 492   // In the 64-bit vm, a size_t can overflow a jlong (which is signed).
 493   NOT_LP64 (return (jlong)val;)
 494   LP64_ONLY(return (jlong)MIN2(val, (size_t)max_jlong);)
 495 }
 496 
 497 JVM_ENTRY_NO_ENV(jlong, JVM_TotalMemory(void))
 498   JVMWrapper("JVM_TotalMemory");
 499   size_t n = Universe::heap()->capacity();
 500   return convert_size_t_to_jlong(n);
 501 JVM_END
 502 
 503 
 504 JVM_ENTRY_NO_ENV(jlong, JVM_FreeMemory(void))
 505   JVMWrapper("JVM_FreeMemory");
 506   CollectedHeap* ch = Universe::heap();
 507   size_t n;
 508   {
 509      MutexLocker x(Heap_lock);
 510      n = ch->capacity() - ch->used();
 511   }
 512   return convert_size_t_to_jlong(n);
 513 JVM_END
 514 
 515 
 516 JVM_ENTRY_NO_ENV(jlong, JVM_MaxMemory(void))
 517   JVMWrapper("JVM_MaxMemory");
 518   size_t n = Universe::heap()->max_capacity();
 519   return convert_size_t_to_jlong(n);
 520 JVM_END
 521 
 522 
 523 JVM_ENTRY_NO_ENV(jint, JVM_ActiveProcessorCount(void))
 524   JVMWrapper("JVM_ActiveProcessorCount");
 525   return os::active_processor_count();
 526 JVM_END
 527 
 528 
 529 JVM_ENTRY_NO_ENV(jboolean, JVM_IsUseContainerSupport(void))
 530   JVMWrapper("JVM_IsUseContainerSupport");
 531 #ifdef TARGET_OS_FAMILY_linux
 532   if (UseContainerSupport) {
 533       return JNI_TRUE;
 534   }
 535 #endif
 536   return JNI_FALSE;
 537 JVM_END
 538 
 539 
 540 
 541 // java.lang.Throwable //////////////////////////////////////////////////////
 542 
 543 
 544 JVM_ENTRY(void, JVM_FillInStackTrace(JNIEnv *env, jobject receiver))
 545   JVMWrapper("JVM_FillInStackTrace");
 546   Handle exception(thread, JNIHandles::resolve_non_null(receiver));
 547   java_lang_Throwable::fill_in_stack_trace(exception);
 548 JVM_END
 549 
 550 
 551 JVM_ENTRY(jint, JVM_GetStackTraceDepth(JNIEnv *env, jobject throwable))
 552   JVMWrapper("JVM_GetStackTraceDepth");
 553   oop exception = JNIHandles::resolve(throwable);
 554   return java_lang_Throwable::get_stack_trace_depth(exception, THREAD);
 555 JVM_END
 556 
 557 
 558 JVM_ENTRY(jobject, JVM_GetStackTraceElement(JNIEnv *env, jobject throwable, jint index))
 559   JVMWrapper("JVM_GetStackTraceElement");
 560   JvmtiVMObjectAllocEventCollector oam; // This ctor (throughout this module) may trigger a safepoint/GC
 561   oop exception = JNIHandles::resolve(throwable);
 562   oop element = java_lang_Throwable::get_stack_trace_element(exception, index, CHECK_NULL);
 563   return JNIHandles::make_local(env, element);
 564 JVM_END
 565 
 566 
 567 // java.lang.Object ///////////////////////////////////////////////
 568 
 569 
 570 JVM_ENTRY(jint, JVM_IHashCode(JNIEnv* env, jobject handle))
 571   JVMWrapper("JVM_IHashCode");
 572   // as implemented in the classic virtual machine; return 0 if object is NULL
 573   return handle == NULL ? 0 : ObjectSynchronizer::FastHashCode (THREAD, JNIHandles::resolve_non_null(handle)) ;
 574 JVM_END
 575 
 576 
 577 JVM_ENTRY(void, JVM_MonitorWait(JNIEnv* env, jobject handle, jlong ms))
 578   JVMWrapper("JVM_MonitorWait");
 579   Handle obj(THREAD, JNIHandles::resolve_non_null(handle));
 580   JavaThreadInObjectWaitState jtiows(thread, ms != 0);
 581   if (JvmtiExport::should_post_monitor_wait()) {
 582     JvmtiExport::post_monitor_wait((JavaThread *)THREAD, (oop)obj(), ms);
 583 
 584     // The current thread already owns the monitor and it has not yet
 585     // been added to the wait queue so the current thread cannot be
 586     // made the successor. This means that the JVMTI_EVENT_MONITOR_WAIT
 587     // event handler cannot accidentally consume an unpark() meant for
 588     // the ParkEvent associated with this ObjectMonitor.
 589   }
 590   ObjectSynchronizer::wait(obj, ms, CHECK);
 591 JVM_END
 592 
 593 
 594 JVM_ENTRY(void, JVM_MonitorNotify(JNIEnv* env, jobject handle))
 595   JVMWrapper("JVM_MonitorNotify");
 596   Handle obj(THREAD, JNIHandles::resolve_non_null(handle));
 597   ObjectSynchronizer::notify(obj, CHECK);
 598 JVM_END
 599 
 600 
 601 JVM_ENTRY(void, JVM_MonitorNotifyAll(JNIEnv* env, jobject handle))
 602   JVMWrapper("JVM_MonitorNotifyAll");
 603   Handle obj(THREAD, JNIHandles::resolve_non_null(handle));
 604   ObjectSynchronizer::notifyall(obj, CHECK);
 605 JVM_END
 606 
 607 
 608 static void fixup_cloned_reference(ReferenceType ref_type, oop src, oop clone) {
 609   // If G1 is enabled then we need to register a non-null referent
 610   // with the SATB barrier.
 611 #if INCLUDE_ALL_GCS
 612   if (UseG1GC) {
 613     oop referent = java_lang_ref_Reference::referent(clone);
 614     if (referent != NULL) {
 615       G1SATBCardTableModRefBS::enqueue(referent);
 616     }
 617   }
 618 #endif // INCLUDE_ALL_GCS
 619   if ((java_lang_ref_Reference::next(clone) != NULL) ||
 620       (java_lang_ref_Reference::queue(clone) == java_lang_ref_ReferenceQueue::ENQUEUED_queue())) {
 621     // If the source has been enqueued or is being enqueued, don't
 622     // register the clone with a queue.
 623     java_lang_ref_Reference::set_queue(clone, java_lang_ref_ReferenceQueue::NULL_queue());
 624   }
 625   // discovered and next are list links; the clone is not in those lists.
 626   java_lang_ref_Reference::set_discovered(clone, NULL);
 627   java_lang_ref_Reference::set_next(clone, NULL);
 628 }
 629 
 630 JVM_ENTRY(jobject, JVM_Clone(JNIEnv* env, jobject handle))
 631   JVMWrapper("JVM_Clone");
 632   Handle obj(THREAD, JNIHandles::resolve_non_null(handle));
 633   const KlassHandle klass (THREAD, obj->klass());
 634   JvmtiVMObjectAllocEventCollector oam;
 635 
 636 #ifdef ASSERT
 637   // Just checking that the cloneable flag is set correct
 638   if (obj->is_array()) {
 639     guarantee(klass->is_cloneable(), "all arrays are cloneable");
 640   } else {
 641     guarantee(obj->is_instance(), "should be instanceOop");
 642     bool cloneable = klass->is_subtype_of(SystemDictionary::Cloneable_klass());
 643     guarantee(cloneable == klass->is_cloneable(), "incorrect cloneable flag");
 644   }
 645 #endif
 646 
 647   // Check if class of obj supports the Cloneable interface.
 648   // All arrays are considered to be cloneable (See JLS 20.1.5)
 649   if (!klass->is_cloneable()) {
 650     ResourceMark rm(THREAD);
 651     THROW_MSG_0(vmSymbols::java_lang_CloneNotSupportedException(), klass->external_name());
 652   }
 653 
 654   // Make shallow object copy
 655   ReferenceType ref_type = REF_NONE;
 656   const int size = obj->size();
 657   oop new_obj_oop = NULL;
 658   if (obj->is_array()) {
 659     const int length = ((arrayOop)obj())->length();
 660     new_obj_oop = CollectedHeap::array_allocate(klass, size, length, CHECK_NULL);
 661   } else {
 662     ref_type = InstanceKlass::cast(klass())->reference_type();
 663     assert((ref_type == REF_NONE) ==
 664            !klass->is_subclass_of(SystemDictionary::Reference_klass()),
 665            "invariant");
 666     new_obj_oop = CollectedHeap::obj_allocate(klass, size, CHECK_NULL);
 667   }
 668 
 669   // 4839641 (4840070): We must do an oop-atomic copy, because if another thread
 670   // is modifying a reference field in the clonee, a non-oop-atomic copy might
 671   // be suspended in the middle of copying the pointer and end up with parts
 672   // of two different pointers in the field.  Subsequent dereferences will crash.
 673   // 4846409: an oop-copy of objects with long or double fields or arrays of same
 674   // won't copy the longs/doubles atomically in 32-bit vm's, so we copy jlongs instead
 675   // of oops.  We know objects are aligned on a minimum of an jlong boundary.
 676   // The same is true of StubRoutines::object_copy and the various oop_copy
 677   // variants, and of the code generated by the inline_native_clone intrinsic.
 678   assert(MinObjAlignmentInBytes >= BytesPerLong, "objects misaligned");
 679   Copy::conjoint_jlongs_atomic((jlong*)obj(), (jlong*)new_obj_oop,
 680                                (size_t)align_object_size(size) / HeapWordsPerLong);
 681   // Clear the header
 682   new_obj_oop->init_mark();
 683 
 684   // Store check (mark entire object and let gc sort it out)
 685   BarrierSet* bs = Universe::heap()->barrier_set();
 686   assert(bs->has_write_region_opt(), "Barrier set does not have write_region");
 687   bs->write_region(MemRegion((HeapWord*)new_obj_oop, size));
 688 
 689   // If cloning a Reference, set Reference fields to a safe state.
 690   // Fixup must be completed before any safepoint.
 691   if (ref_type != REF_NONE) {
 692     fixup_cloned_reference(ref_type, obj(), new_obj_oop);
 693   }
 694 
 695   Handle new_obj(THREAD, new_obj_oop);
 696   // Special handling for MemberNames.  Since they contain Method* metadata, they
 697   // must be registered so that RedefineClasses can fix metadata contained in them.
 698   if (java_lang_invoke_MemberName::is_instance(new_obj()) &&
 699       java_lang_invoke_MemberName::is_method(new_obj())) {
 700     Method* method = (Method*)java_lang_invoke_MemberName::vmtarget(new_obj());
 701     // MemberName may be unresolved, so doesn't need registration until resolved.
 702     if (method != NULL) {
 703       methodHandle m(THREAD, method);
 704       // This can safepoint and redefine method, so need both new_obj and method
 705       // in a handle, for two different reasons.  new_obj can move, method can be
 706       // deleted if nothing is using it on the stack.
 707       m->method_holder()->add_member_name(new_obj(), false);
 708     }
 709   }
 710 
 711   // Caution: this involves a java upcall, so the clone should be
 712   // "gc-robust" by this stage.
 713   if (klass->has_finalizer()) {
 714     assert(obj->is_instance(), "should be instanceOop");
 715     new_obj_oop = InstanceKlass::register_finalizer(instanceOop(new_obj()), CHECK_NULL);
 716     new_obj = Handle(THREAD, new_obj_oop);
 717   }
 718 
 719   return JNIHandles::make_local(env, new_obj());
 720 JVM_END
 721 
 722 // java.lang.Compiler ////////////////////////////////////////////////////
 723 
 724 // The initial cuts of the HotSpot VM will not support JITs, and all existing
 725 // JITs would need extensive changes to work with HotSpot.  The JIT-related JVM
 726 // functions are all silently ignored unless JVM warnings are printed.
 727 
 728 JVM_LEAF(void, JVM_InitializeCompiler (JNIEnv *env, jclass compCls))
 729   if (PrintJVMWarnings) warning("JVM_InitializeCompiler not supported");
 730 JVM_END
 731 
 732 
 733 JVM_LEAF(jboolean, JVM_IsSilentCompiler(JNIEnv *env, jclass compCls))
 734   if (PrintJVMWarnings) warning("JVM_IsSilentCompiler not supported");
 735   return JNI_FALSE;
 736 JVM_END
 737 
 738 
 739 JVM_LEAF(jboolean, JVM_CompileClass(JNIEnv *env, jclass compCls, jclass cls))
 740   if (PrintJVMWarnings) warning("JVM_CompileClass not supported");
 741   return JNI_FALSE;
 742 JVM_END
 743 
 744 
 745 JVM_LEAF(jboolean, JVM_CompileClasses(JNIEnv *env, jclass cls, jstring jname))
 746   if (PrintJVMWarnings) warning("JVM_CompileClasses not supported");
 747   return JNI_FALSE;
 748 JVM_END
 749 
 750 
 751 JVM_LEAF(jobject, JVM_CompilerCommand(JNIEnv *env, jclass compCls, jobject arg))
 752   if (PrintJVMWarnings) warning("JVM_CompilerCommand not supported");
 753   return NULL;
 754 JVM_END
 755 
 756 
 757 JVM_LEAF(void, JVM_EnableCompiler(JNIEnv *env, jclass compCls))
 758   if (PrintJVMWarnings) warning("JVM_EnableCompiler not supported");
 759 JVM_END
 760 
 761 
 762 JVM_LEAF(void, JVM_DisableCompiler(JNIEnv *env, jclass compCls))
 763   if (PrintJVMWarnings) warning("JVM_DisableCompiler not supported");
 764 JVM_END
 765 
 766 
 767 
 768 // Error message support //////////////////////////////////////////////////////
 769 
 770 JVM_LEAF(jint, JVM_GetLastErrorString(char *buf, int len))
 771   JVMWrapper("JVM_GetLastErrorString");
 772   return (jint)os::lasterror(buf, len);
 773 JVM_END
 774 
 775 
 776 // java.io.File ///////////////////////////////////////////////////////////////
 777 
 778 JVM_LEAF(char*, JVM_NativePath(char* path))
 779   JVMWrapper2("JVM_NativePath (%s)", path);
 780   return os::native_path(path);
 781 JVM_END
 782 
 783 
 784 // java.nio.Bits ///////////////////////////////////////////////////////////////
 785 
 786 #define MAX_OBJECT_SIZE \
 787   ( arrayOopDesc::header_size(T_DOUBLE) * HeapWordSize \
 788     + ((julong)max_jint * sizeof(double)) )
 789 
 790 static inline jlong field_offset_to_byte_offset(jlong field_offset) {
 791   return field_offset;
 792 }
 793 
 794 static inline void assert_field_offset_sane(oop p, jlong field_offset) {
 795 #ifdef ASSERT
 796   jlong byte_offset = field_offset_to_byte_offset(field_offset);
 797 
 798   if (p != NULL) {
 799     assert(byte_offset >= 0 && byte_offset <= (jlong)MAX_OBJECT_SIZE, "sane offset");
 800     if (byte_offset == (jint)byte_offset) {
 801       void* ptr_plus_disp = (address)p + byte_offset;
 802       assert((void*)p->obj_field_addr<oop>((jint)byte_offset) == ptr_plus_disp,
 803              "raw [ptr+disp] must be consistent with oop::field_base");
 804     }
 805     jlong p_size = HeapWordSize * (jlong)(p->size());
 806     assert(byte_offset < p_size, err_msg("Unsafe access: offset " INT64_FORMAT
 807                                          " > object's size " INT64_FORMAT,
 808                                          (int64_t)byte_offset, (int64_t)p_size));
 809   }
 810 #endif
 811 }
 812 
 813 static inline void* index_oop_from_field_offset_long(oop p, jlong field_offset) {
 814   assert_field_offset_sane(p, field_offset);
 815   jlong byte_offset = field_offset_to_byte_offset(field_offset);
 816 
 817   if (sizeof(char*) == sizeof(jint)) {   // (this constant folds!)
 818     return (address)p + (jint) byte_offset;
 819   } else {
 820     return (address)p +        byte_offset;
 821   }
 822 }
 823 
 824 // This function is a leaf since if the source and destination are both in native memory
 825 // the copy may potentially be very large, and we don't want to disable GC if we can avoid it.
 826 // If either source or destination (or both) are on the heap, the function will enter VM using
 827 // JVM_ENTRY_FROM_LEAF
 828 JVM_LEAF(void, JVM_CopySwapMemory(JNIEnv *env, jobject srcObj, jlong srcOffset,
 829                                   jobject dstObj, jlong dstOffset, jlong size,
 830                                   jlong elemSize)) {
 831 
 832   size_t sz = (size_t)size;
 833   size_t esz = (size_t)elemSize;
 834 
 835   if (srcObj == NULL && dstObj == NULL) {
 836     // Both src & dst are in native memory
 837     address src = (address)srcOffset;
 838     address dst = (address)dstOffset;
 839 
 840     Copy::conjoint_swap(src, dst, sz, esz);
 841   } else {
 842     // At least one of src/dst are on heap, transition to VM to access raw pointers
 843 
 844     JVM_ENTRY_FROM_LEAF(env, void, JVM_CopySwapMemory) {
 845       oop srcp = JNIHandles::resolve(srcObj);
 846       oop dstp = JNIHandles::resolve(dstObj);
 847 
 848       address src = (address)index_oop_from_field_offset_long(srcp, srcOffset);
 849       address dst = (address)index_oop_from_field_offset_long(dstp, dstOffset);
 850 
 851       Copy::conjoint_swap(src, dst, sz, esz);
 852     } JVM_END
 853   }
 854 } JVM_END
 855 
 856 
 857 // Misc. class handling ///////////////////////////////////////////////////////////
 858 
 859 
 860 JVM_ENTRY(jclass, JVM_GetCallerClass(JNIEnv* env, int depth))
 861   JVMWrapper("JVM_GetCallerClass");
 862 
 863   // Pre-JDK 8 and early builds of JDK 8 don't have a CallerSensitive annotation; or
 864   // sun.reflect.Reflection.getCallerClass with a depth parameter is provided
 865   // temporarily for existing code to use until a replacement API is defined.
 866   if (SystemDictionary::reflect_CallerSensitive_klass() == NULL || depth != JVM_CALLER_DEPTH) {
 867     Klass* k = thread->security_get_caller_class(depth);
 868     return (k == NULL) ? NULL : (jclass) JNIHandles::make_local(env, k->java_mirror());
 869   }
 870 
 871   // Getting the class of the caller frame.
 872   //
 873   // The call stack at this point looks something like this:
 874   //
 875   // [0] [ @CallerSensitive public sun.reflect.Reflection.getCallerClass ]
 876   // [1] [ @CallerSensitive API.method                                   ]
 877   // [.] [ (skipped intermediate frames)                                 ]
 878   // [n] [ caller                                                        ]
 879   vframeStream vfst(thread);
 880   // Cf. LibraryCallKit::inline_native_Reflection_getCallerClass
 881   for (int n = 0; !vfst.at_end(); vfst.security_next(), n++) {
 882     Method* m = vfst.method();
 883     assert(m != NULL, "sanity");
 884     switch (n) {
 885     case 0:
 886       // This must only be called from Reflection.getCallerClass
 887       if (m->intrinsic_id() != vmIntrinsics::_getCallerClass) {
 888         THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), "JVM_GetCallerClass must only be called from Reflection.getCallerClass");
 889       }
 890       // fall-through
 891     case 1:
 892       // Frame 0 and 1 must be caller sensitive.
 893       if (!m->caller_sensitive()) {
 894         THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), err_msg("CallerSensitive annotation expected at frame %d", n));
 895       }
 896       break;
 897     default:
 898       if (!m->is_ignored_by_security_stack_walk()) {
 899         // We have reached the desired frame; return the holder class.
 900         return (jclass) JNIHandles::make_local(env, m->method_holder()->java_mirror());
 901       }
 902       break;
 903     }
 904   }
 905   return NULL;
 906 JVM_END
 907 
 908 
 909 JVM_ENTRY(jclass, JVM_FindPrimitiveClass(JNIEnv* env, const char* utf))
 910   JVMWrapper("JVM_FindPrimitiveClass");
 911   oop mirror = NULL;
 912   BasicType t = name2type(utf);
 913   if (t != T_ILLEGAL && t != T_OBJECT && t != T_ARRAY) {
 914     mirror = Universe::java_mirror(t);
 915   }
 916   if (mirror == NULL) {
 917     THROW_MSG_0(vmSymbols::java_lang_ClassNotFoundException(), (char*) utf);
 918   } else {
 919     return (jclass) JNIHandles::make_local(env, mirror);
 920   }
 921 JVM_END
 922 
 923 
 924 JVM_ENTRY(void, JVM_ResolveClass(JNIEnv* env, jclass cls))
 925   JVMWrapper("JVM_ResolveClass");
 926   if (PrintJVMWarnings) warning("JVM_ResolveClass not implemented");
 927 JVM_END
 928 
 929 
 930 JVM_ENTRY(jboolean, JVM_KnownToNotExist(JNIEnv *env, jobject loader, const char *classname))
 931   JVMWrapper("JVM_KnownToNotExist");
 932 #if INCLUDE_CDS
 933   return ClassLoaderExt::known_to_not_exist(env, loader, classname, THREAD);
 934 #else
 935   return false;
 936 #endif
 937 JVM_END
 938 
 939 
 940 JVM_ENTRY(jobjectArray, JVM_GetResourceLookupCacheURLs(JNIEnv *env, jobject loader))
 941   JVMWrapper("JVM_GetResourceLookupCacheURLs");
 942 #if INCLUDE_CDS
 943   return ClassLoaderExt::get_lookup_cache_urls(env, loader, THREAD);
 944 #else
 945   return NULL;
 946 #endif
 947 JVM_END
 948 
 949 
 950 JVM_ENTRY(jintArray, JVM_GetResourceLookupCache(JNIEnv *env, jobject loader, const char *resource_name))
 951   JVMWrapper("JVM_GetResourceLookupCache");
 952 #if INCLUDE_CDS
 953   return ClassLoaderExt::get_lookup_cache(env, loader, resource_name, THREAD);
 954 #else
 955   return NULL;
 956 #endif
 957 JVM_END
 958 
 959 
 960 // Returns a class loaded by the bootstrap class loader; or null
 961 // if not found.  ClassNotFoundException is not thrown.
 962 //
 963 // Rationale behind JVM_FindClassFromBootLoader
 964 // a> JVM_FindClassFromClassLoader was never exported in the export tables.
 965 // b> because of (a) java.dll has a direct dependecy on the  unexported
 966 //    private symbol "_JVM_FindClassFromClassLoader@20".
 967 // c> the launcher cannot use the private symbol as it dynamically opens
 968 //    the entry point, so if something changes, the launcher will fail
 969 //    unexpectedly at runtime, it is safest for the launcher to dlopen a
 970 //    stable exported interface.
 971 // d> re-exporting JVM_FindClassFromClassLoader as public, will cause its
 972 //    signature to change from _JVM_FindClassFromClassLoader@20 to
 973 //    JVM_FindClassFromClassLoader and will not be backward compatible
 974 //    with older JDKs.
 975 // Thus a public/stable exported entry point is the right solution,
 976 // public here means public in linker semantics, and is exported only
 977 // to the JDK, and is not intended to be a public API.
 978 
 979 JVM_ENTRY(jclass, JVM_FindClassFromBootLoader(JNIEnv* env,
 980                                               const char* name))
 981   JVMWrapper2("JVM_FindClassFromBootLoader %s", name);
 982 
 983   // Java libraries should ensure that name is never null...
 984   if (name == NULL || (int)strlen(name) > Symbol::max_length()) {
 985     // It's impossible to create this class;  the name cannot fit
 986     // into the constant pool.
 987     return NULL;
 988   }
 989 
 990   TempNewSymbol h_name = SymbolTable::new_symbol(name, CHECK_NULL);
 991   Klass* k = SystemDictionary::resolve_or_null(h_name, CHECK_NULL);
 992   if (k == NULL) {
 993     return NULL;
 994   }
 995 
 996   if (TraceClassResolution) {
 997     trace_class_resolution(k);
 998   }
 999   return (jclass) JNIHandles::make_local(env, k->java_mirror());
1000 JVM_END
1001 
1002 // Not used; JVM_FindClassFromCaller replaces this.
1003 JVM_ENTRY(jclass, JVM_FindClassFromClassLoader(JNIEnv* env, const char* name,
1004                                                jboolean init, jobject loader,
1005                                                jboolean throwError))
1006   JVMWrapper3("JVM_FindClassFromClassLoader %s throw %s", name,
1007                throwError ? "error" : "exception");
1008   // Java libraries should ensure that name is never null...
1009   if (name == NULL || (int)strlen(name) > Symbol::max_length()) {
1010     // It's impossible to create this class;  the name cannot fit
1011     // into the constant pool.
1012     if (throwError) {
1013       THROW_MSG_0(vmSymbols::java_lang_NoClassDefFoundError(), name);
1014     } else {
1015       THROW_MSG_0(vmSymbols::java_lang_ClassNotFoundException(), name);
1016     }
1017   }
1018   TempNewSymbol h_name = SymbolTable::new_symbol(name, CHECK_NULL);
1019   Handle h_loader(THREAD, JNIHandles::resolve(loader));
1020   jclass result = find_class_from_class_loader(env, h_name, init, h_loader,
1021                                                Handle(), throwError, THREAD);
1022 
1023   if (TraceClassResolution && result != NULL) {
1024     trace_class_resolution(java_lang_Class::as_Klass(JNIHandles::resolve_non_null(result)));
1025   }
1026   return result;
1027 JVM_END
1028 
1029 // Find a class with this name in this loader, using the caller's protection domain.
1030 JVM_ENTRY(jclass, JVM_FindClassFromCaller(JNIEnv* env, const char* name,
1031                                           jboolean init, jobject loader,
1032                                           jclass caller))
1033   JVMWrapper2("JVM_FindClassFromCaller %s throws ClassNotFoundException", name);
1034   // Java libraries should ensure that name is never null...
1035   if (name == NULL || (int)strlen(name) > Symbol::max_length()) {
1036     // It's impossible to create this class;  the name cannot fit
1037     // into the constant pool.
1038     THROW_MSG_0(vmSymbols::java_lang_ClassNotFoundException(), name);
1039   }
1040 
1041   TempNewSymbol h_name = SymbolTable::new_symbol(name, CHECK_NULL);
1042 
1043   oop loader_oop = JNIHandles::resolve(loader);
1044   oop from_class = JNIHandles::resolve(caller);
1045   oop protection_domain = NULL;
1046   // If loader is null, shouldn't call ClassLoader.checkPackageAccess; otherwise get
1047   // NPE. Put it in another way, the bootstrap class loader has all permission and
1048   // thus no checkPackageAccess equivalence in the VM class loader.
1049   // The caller is also passed as NULL by the java code if there is no security
1050   // manager to avoid the performance cost of getting the calling class.
1051   if (from_class != NULL && loader_oop != NULL) {
1052     protection_domain = java_lang_Class::as_Klass(from_class)->protection_domain();
1053   }
1054 
1055   Handle h_loader(THREAD, loader_oop);
1056   Handle h_prot(THREAD, protection_domain);
1057   jclass result = find_class_from_class_loader(env, h_name, init, h_loader,
1058                                                h_prot, false, THREAD);
1059 
1060   if (TraceClassResolution && result != NULL) {
1061     trace_class_resolution(java_lang_Class::as_Klass(JNIHandles::resolve_non_null(result)));
1062   }
1063   return result;
1064 JVM_END
1065 
1066 JVM_ENTRY(jclass, JVM_FindClassFromClass(JNIEnv *env, const char *name,
1067                                          jboolean init, jclass from))
1068   JVMWrapper2("JVM_FindClassFromClass %s", name);
1069   if (name == NULL || (int)strlen(name) > Symbol::max_length()) {
1070     // It's impossible to create this class;  the name cannot fit
1071     // into the constant pool.
1072     THROW_MSG_0(vmSymbols::java_lang_NoClassDefFoundError(), name);
1073   }
1074   TempNewSymbol h_name = SymbolTable::new_symbol(name, CHECK_NULL);
1075   oop from_class_oop = JNIHandles::resolve(from);
1076   Klass* from_class = (from_class_oop == NULL)
1077                            ? (Klass*)NULL
1078                            : java_lang_Class::as_Klass(from_class_oop);
1079   oop class_loader = NULL;
1080   oop protection_domain = NULL;
1081   if (from_class != NULL) {
1082     class_loader = from_class->class_loader();
1083     protection_domain = from_class->protection_domain();
1084   }
1085   Handle h_loader(THREAD, class_loader);
1086   Handle h_prot  (THREAD, protection_domain);
1087   jclass result = find_class_from_class_loader(env, h_name, init, h_loader,
1088                                                h_prot, true, thread);
1089 
1090   if (TraceClassResolution && result != NULL) {
1091     // this function is generally only used for class loading during verification.
1092     ResourceMark rm;
1093     oop from_mirror = JNIHandles::resolve_non_null(from);
1094     Klass* from_class = java_lang_Class::as_Klass(from_mirror);
1095     const char * from_name = from_class->external_name();
1096 
1097     oop mirror = JNIHandles::resolve_non_null(result);
1098     Klass* to_class = java_lang_Class::as_Klass(mirror);
1099     const char * to = to_class->external_name();
1100     tty->print("RESOLVE %s %s (verification)\n", from_name, to);
1101   }
1102 
1103   return result;
1104 JVM_END
1105 
1106 static void is_lock_held_by_thread(Handle loader, PerfCounter* counter, TRAPS) {
1107   if (loader.is_null()) {
1108     return;
1109   }
1110 
1111   // check whether the current caller thread holds the lock or not.
1112   // If not, increment the corresponding counter
1113   if (ObjectSynchronizer::query_lock_ownership((JavaThread*)THREAD, loader) !=
1114       ObjectSynchronizer::owner_self) {
1115     counter->inc();
1116   }
1117 }
1118 
1119 // common code for JVM_DefineClass() and JVM_DefineClassWithSource()
1120 // and JVM_DefineClassWithSourceCond()
1121 static jclass jvm_define_class_common(JNIEnv *env, const char *name,
1122                                       jobject loader, const jbyte *buf,
1123                                       jsize len, jobject pd, const char *source,
1124                                       jboolean verify, TRAPS) {
1125   if (source == NULL)  source = "__JVM_DefineClass__";
1126 
1127   assert(THREAD->is_Java_thread(), "must be a JavaThread");
1128   JavaThread* jt = (JavaThread*) THREAD;
1129 
1130   PerfClassTraceTime vmtimer(ClassLoader::perf_define_appclass_time(),
1131                              ClassLoader::perf_define_appclass_selftime(),
1132                              ClassLoader::perf_define_appclasses(),
1133                              jt->get_thread_stat()->perf_recursion_counts_addr(),
1134                              jt->get_thread_stat()->perf_timers_addr(),
1135                              PerfClassTraceTime::DEFINE_CLASS);
1136 
1137   if (UsePerfData) {
1138     ClassLoader::perf_app_classfile_bytes_read()->inc(len);
1139   }
1140 
1141   // Since exceptions can be thrown, class initialization can take place
1142   // if name is NULL no check for class name in .class stream has to be made.
1143   TempNewSymbol class_name = NULL;
1144   if (name != NULL) {
1145     const int str_len = (int)strlen(name);
1146     if (str_len > Symbol::max_length()) {
1147       // It's impossible to create this class;  the name cannot fit
1148       // into the constant pool.
1149       THROW_MSG_0(vmSymbols::java_lang_NoClassDefFoundError(), name);
1150     }
1151     class_name = SymbolTable::new_symbol(name, str_len, CHECK_NULL);
1152   }
1153 
1154   ResourceMark rm(THREAD);
1155   ClassFileStream st((u1*) buf, len, (char *)source);
1156   Handle class_loader (THREAD, JNIHandles::resolve(loader));
1157   if (UsePerfData) {
1158     is_lock_held_by_thread(class_loader,
1159                            ClassLoader::sync_JVMDefineClassLockFreeCounter(),
1160                            THREAD);
1161   }
1162   Handle protection_domain (THREAD, JNIHandles::resolve(pd));
1163   Klass* k = SystemDictionary::resolve_from_stream(class_name, class_loader,
1164                                                      protection_domain, &st,
1165                                                      verify != 0,
1166                                                      CHECK_NULL);
1167 
1168   if (TraceClassResolution && k != NULL) {
1169     trace_class_resolution(k);
1170   }
1171 
1172   return (jclass) JNIHandles::make_local(env, k->java_mirror());
1173 }
1174 
1175 
1176 JVM_ENTRY(jclass, JVM_DefineClass(JNIEnv *env, const char *name, jobject loader, const jbyte *buf, jsize len, jobject pd))
1177   JVMWrapper2("JVM_DefineClass %s", name);
1178 
1179   return jvm_define_class_common(env, name, loader, buf, len, pd, NULL, true, THREAD);
1180 JVM_END
1181 
1182 
1183 JVM_ENTRY(jclass, JVM_DefineClassWithSource(JNIEnv *env, const char *name, jobject loader, const jbyte *buf, jsize len, jobject pd, const char *source))
1184   JVMWrapper2("JVM_DefineClassWithSource %s", name);
1185 
1186   return jvm_define_class_common(env, name, loader, buf, len, pd, source, true, THREAD);
1187 JVM_END
1188 
1189 JVM_ENTRY(jclass, JVM_DefineClassWithSourceCond(JNIEnv *env, const char *name,
1190                                                 jobject loader, const jbyte *buf,
1191                                                 jsize len, jobject pd,
1192                                                 const char *source, jboolean verify))
1193   JVMWrapper2("JVM_DefineClassWithSourceCond %s", name);
1194 
1195   return jvm_define_class_common(env, name, loader, buf, len, pd, source, verify, THREAD);
1196 JVM_END
1197 
1198 JVM_ENTRY(jclass, JVM_FindLoadedClass(JNIEnv *env, jobject loader, jstring name))
1199   JVMWrapper("JVM_FindLoadedClass");
1200   ResourceMark rm(THREAD);
1201 
1202   Handle h_name (THREAD, JNIHandles::resolve_non_null(name));
1203   Handle string = java_lang_String::internalize_classname(h_name, CHECK_NULL);
1204 
1205   const char* str   = java_lang_String::as_utf8_string(string());
1206   // Sanity check, don't expect null
1207   if (str == NULL) return NULL;
1208 
1209   const int str_len = (int)strlen(str);
1210   if (str_len > Symbol::max_length()) {
1211     // It's impossible to create this class;  the name cannot fit
1212     // into the constant pool.
1213     return NULL;
1214   }
1215   TempNewSymbol klass_name = SymbolTable::new_symbol(str, str_len, CHECK_NULL);
1216 
1217   // Security Note:
1218   //   The Java level wrapper will perform the necessary security check allowing
1219   //   us to pass the NULL as the initiating class loader.
1220   Handle h_loader(THREAD, JNIHandles::resolve(loader));
1221   if (UsePerfData) {
1222     is_lock_held_by_thread(h_loader,
1223                            ClassLoader::sync_JVMFindLoadedClassLockFreeCounter(),
1224                            THREAD);
1225   }
1226 
1227   Klass* k = SystemDictionary::find_instance_or_array_klass(klass_name,
1228                                                               h_loader,
1229                                                               Handle(),
1230                                                               CHECK_NULL);
1231 #if INCLUDE_CDS
1232   if (k == NULL) {
1233     // If the class is not already loaded, try to see if it's in the shared
1234     // archive for the current classloader (h_loader).
1235     instanceKlassHandle ik = SystemDictionaryShared::find_or_load_shared_class(
1236         klass_name, h_loader, CHECK_NULL);
1237     k = ik();
1238   }
1239 #endif
1240   return (k == NULL) ? NULL :
1241             (jclass) JNIHandles::make_local(env, k->java_mirror());
1242 JVM_END
1243 
1244 
1245 // Reflection support //////////////////////////////////////////////////////////////////////////////
1246 
1247 JVM_ENTRY(jstring, JVM_GetClassName(JNIEnv *env, jclass cls))
1248   assert (cls != NULL, "illegal class");
1249   JVMWrapper("JVM_GetClassName");
1250   JvmtiVMObjectAllocEventCollector oam;
1251   ResourceMark rm(THREAD);
1252   const char* name;
1253   if (java_lang_Class::is_primitive(JNIHandles::resolve(cls))) {
1254     name = type2name(java_lang_Class::primitive_type(JNIHandles::resolve(cls)));
1255   } else {
1256     // Consider caching interned string in Klass
1257     Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve(cls));
1258     assert(k->is_klass(), "just checking");
1259     name = k->external_name();
1260   }
1261   oop result = StringTable::intern((char*) name, CHECK_NULL);
1262   return (jstring) JNIHandles::make_local(env, result);
1263 JVM_END
1264 
1265 
1266 JVM_ENTRY(jobjectArray, JVM_GetClassInterfaces(JNIEnv *env, jclass cls))
1267   JVMWrapper("JVM_GetClassInterfaces");
1268   JvmtiVMObjectAllocEventCollector oam;
1269   oop mirror = JNIHandles::resolve_non_null(cls);
1270 
1271   // Special handling for primitive objects
1272   if (java_lang_Class::is_primitive(mirror)) {
1273     // Primitive objects does not have any interfaces
1274     objArrayOop r = oopFactory::new_objArray(SystemDictionary::Class_klass(), 0, CHECK_NULL);
1275     return (jobjectArray) JNIHandles::make_local(env, r);
1276   }
1277 
1278   KlassHandle klass(thread, java_lang_Class::as_Klass(mirror));
1279   // Figure size of result array
1280   int size;
1281   if (klass->oop_is_instance()) {
1282     size = InstanceKlass::cast(klass())->local_interfaces()->length();
1283   } else {
1284     assert(klass->oop_is_objArray() || klass->oop_is_typeArray(), "Illegal mirror klass");
1285     size = 2;
1286   }
1287 
1288   // Allocate result array
1289   objArrayOop r = oopFactory::new_objArray(SystemDictionary::Class_klass(), size, CHECK_NULL);
1290   objArrayHandle result (THREAD, r);
1291   // Fill in result
1292   if (klass->oop_is_instance()) {
1293     // Regular instance klass, fill in all local interfaces
1294     for (int index = 0; index < size; index++) {
1295       Klass* k = InstanceKlass::cast(klass())->local_interfaces()->at(index);
1296       result->obj_at_put(index, k->java_mirror());
1297     }
1298   } else {
1299     // All arrays implement java.lang.Cloneable and java.io.Serializable
1300     result->obj_at_put(0, SystemDictionary::Cloneable_klass()->java_mirror());
1301     result->obj_at_put(1, SystemDictionary::Serializable_klass()->java_mirror());
1302   }
1303   return (jobjectArray) JNIHandles::make_local(env, result());
1304 JVM_END
1305 
1306 
1307 JVM_ENTRY(jobject, JVM_GetClassLoader(JNIEnv *env, jclass cls))
1308   JVMWrapper("JVM_GetClassLoader");
1309   if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(cls))) {
1310     return NULL;
1311   }
1312   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
1313   oop loader = k->class_loader();
1314   return JNIHandles::make_local(env, loader);
1315 JVM_END
1316 
1317 
1318 JVM_QUICK_ENTRY(jboolean, JVM_IsInterface(JNIEnv *env, jclass cls))
1319   JVMWrapper("JVM_IsInterface");
1320   oop mirror = JNIHandles::resolve_non_null(cls);
1321   if (java_lang_Class::is_primitive(mirror)) {
1322     return JNI_FALSE;
1323   }
1324   Klass* k = java_lang_Class::as_Klass(mirror);
1325   jboolean result = k->is_interface();
1326   assert(!result || k->oop_is_instance(),
1327          "all interfaces are instance types");
1328   // The compiler intrinsic for isInterface tests the
1329   // Klass::_access_flags bits in the same way.
1330   return result;
1331 JVM_END
1332 
1333 
1334 JVM_ENTRY(jobjectArray, JVM_GetClassSigners(JNIEnv *env, jclass cls))
1335   JVMWrapper("JVM_GetClassSigners");
1336   JvmtiVMObjectAllocEventCollector oam;
1337   if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(cls))) {
1338     // There are no signers for primitive types
1339     return NULL;
1340   }
1341 
1342   objArrayOop signers = java_lang_Class::signers(JNIHandles::resolve_non_null(cls));
1343 
1344   // If there are no signers set in the class, or if the class
1345   // is an array, return NULL.
1346   if (signers == NULL) return NULL;
1347 
1348   // copy of the signers array
1349   Klass* element = ObjArrayKlass::cast(signers->klass())->element_klass();
1350   objArrayOop signers_copy = oopFactory::new_objArray(element, signers->length(), CHECK_NULL);
1351   for (int index = 0; index < signers->length(); index++) {
1352     signers_copy->obj_at_put(index, signers->obj_at(index));
1353   }
1354 
1355   // return the copy
1356   return (jobjectArray) JNIHandles::make_local(env, signers_copy);
1357 JVM_END
1358 
1359 
1360 JVM_ENTRY(void, JVM_SetClassSigners(JNIEnv *env, jclass cls, jobjectArray signers))
1361   JVMWrapper("JVM_SetClassSigners");
1362   if (!java_lang_Class::is_primitive(JNIHandles::resolve_non_null(cls))) {
1363     // This call is ignored for primitive types and arrays.
1364     // Signers are only set once, ClassLoader.java, and thus shouldn't
1365     // be called with an array.  Only the bootstrap loader creates arrays.
1366     Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
1367     if (k->oop_is_instance()) {
1368       java_lang_Class::set_signers(k->java_mirror(), objArrayOop(JNIHandles::resolve(signers)));
1369     }
1370   }
1371 JVM_END
1372 
1373 
1374 JVM_ENTRY(jobject, JVM_GetProtectionDomain(JNIEnv *env, jclass cls))
1375   JVMWrapper("JVM_GetProtectionDomain");
1376   if (JNIHandles::resolve(cls) == NULL) {
1377     THROW_(vmSymbols::java_lang_NullPointerException(), NULL);
1378   }
1379 
1380   if (java_lang_Class::is_primitive(JNIHandles::resolve(cls))) {
1381     // Primitive types does not have a protection domain.
1382     return NULL;
1383   }
1384 
1385   oop pd = java_lang_Class::protection_domain(JNIHandles::resolve(cls));
1386   return (jobject) JNIHandles::make_local(env, pd);
1387 JVM_END
1388 
1389 
1390 static bool is_authorized(Handle context, instanceKlassHandle klass, TRAPS) {
1391   // If there is a security manager and protection domain, check the access
1392   // in the protection domain, otherwise it is authorized.
1393   if (java_lang_System::has_security_manager()) {
1394 
1395     // For bootstrapping, if pd implies method isn't in the JDK, allow
1396     // this context to revert to older behavior.
1397     // In this case the isAuthorized field in AccessControlContext is also not
1398     // present.
1399     if (Universe::protection_domain_implies_method() == NULL) {
1400       return true;
1401     }
1402 
1403     // Whitelist certain access control contexts
1404     if (java_security_AccessControlContext::is_authorized(context)) {
1405       return true;
1406     }
1407 
1408     oop prot = klass->protection_domain();
1409     if (prot != NULL) {
1410       // Call pd.implies(new SecurityPermission("createAccessControlContext"))
1411       // in the new wrapper.
1412       methodHandle m(THREAD, Universe::protection_domain_implies_method());
1413       Handle h_prot(THREAD, prot);
1414       JavaValue result(T_BOOLEAN);
1415       JavaCallArguments args(h_prot);
1416       JavaCalls::call(&result, m, &args, CHECK_false);
1417       return (result.get_jboolean() != 0);
1418     }
1419   }
1420   return true;
1421 }
1422 
1423 // Create an AccessControlContext with a protection domain with null codesource
1424 // and null permissions - which gives no permissions.
1425 oop create_dummy_access_control_context(TRAPS) {
1426   InstanceKlass* pd_klass = InstanceKlass::cast(SystemDictionary::ProtectionDomain_klass());
1427   Handle obj = pd_klass->allocate_instance_handle(CHECK_NULL);
1428   // Call constructor ProtectionDomain(null, null);
1429   JavaValue result(T_VOID);
1430   JavaCalls::call_special(&result, obj, KlassHandle(THREAD, pd_klass),
1431                           vmSymbols::object_initializer_name(),
1432                           vmSymbols::codesource_permissioncollection_signature(),
1433                           Handle(), Handle(), CHECK_NULL);
1434 
1435   // new ProtectionDomain[] {pd};
1436   objArrayOop context = oopFactory::new_objArray(pd_klass, 1, CHECK_NULL);
1437   context->obj_at_put(0, obj());
1438 
1439   // new AccessControlContext(new ProtectionDomain[] {pd})
1440   objArrayHandle h_context(THREAD, context);
1441   oop acc = java_security_AccessControlContext::create(h_context, false, Handle(), CHECK_NULL);
1442   return acc;
1443 }
1444 
1445 JVM_ENTRY(jobject, JVM_DoPrivileged(JNIEnv *env, jclass cls, jobject action, jobject context, jboolean wrapException))
1446   JVMWrapper("JVM_DoPrivileged");
1447 
1448   if (action == NULL) {
1449     THROW_MSG_0(vmSymbols::java_lang_NullPointerException(), "Null action");
1450   }
1451 
1452   // Compute the frame initiating the do privileged operation and setup the privileged stack
1453   vframeStream vfst(thread);
1454   vfst.security_get_caller_frame(1);
1455 
1456   if (vfst.at_end()) {
1457     THROW_MSG_0(vmSymbols::java_lang_InternalError(), "no caller?");
1458   }
1459 
1460   Method* method        = vfst.method();
1461   instanceKlassHandle klass (THREAD, method->method_holder());
1462 
1463   // Check that action object understands "Object run()"
1464   Handle h_context;
1465   if (context != NULL) {
1466     h_context = Handle(THREAD, JNIHandles::resolve(context));
1467     bool authorized = is_authorized(h_context, klass, CHECK_NULL);
1468     if (!authorized) {
1469       // Create an unprivileged access control object and call it's run function
1470       // instead.
1471       oop noprivs = create_dummy_access_control_context(CHECK_NULL);
1472       h_context = Handle(THREAD, noprivs);
1473     }
1474   }
1475 
1476   // Check that action object understands "Object run()"
1477   Handle object (THREAD, JNIHandles::resolve(action));
1478 
1479   // get run() method
1480   Method* m_oop = object->klass()->uncached_lookup_method(
1481                                            vmSymbols::run_method_name(),
1482                                            vmSymbols::void_object_signature(),
1483                                            Klass::find_overpass);
1484   methodHandle m (THREAD, m_oop);
1485   if (m.is_null() || !m->is_method() || !m()->is_public() || m()->is_static()) {
1486     THROW_MSG_0(vmSymbols::java_lang_InternalError(), "No run method");
1487   }
1488 
1489   // Stack allocated list of privileged stack elements
1490   PrivilegedElement pi;
1491   if (!vfst.at_end()) {
1492     pi.initialize(&vfst, h_context(), thread->privileged_stack_top(), CHECK_NULL);
1493     thread->set_privileged_stack_top(&pi);
1494   }
1495 
1496 
1497   // invoke the Object run() in the action object. We cannot use call_interface here, since the static type
1498   // is not really known - it is either java.security.PrivilegedAction or java.security.PrivilegedExceptionAction
1499   Handle pending_exception;
1500   JavaValue result(T_OBJECT);
1501   JavaCallArguments args(object);
1502   JavaCalls::call(&result, m, &args, THREAD);
1503 
1504   // done with action, remove ourselves from the list
1505   if (!vfst.at_end()) {
1506     assert(thread->privileged_stack_top() != NULL && thread->privileged_stack_top() == &pi, "wrong top element");
1507     thread->set_privileged_stack_top(thread->privileged_stack_top()->next());
1508   }
1509 
1510   if (HAS_PENDING_EXCEPTION) {
1511     pending_exception = Handle(THREAD, PENDING_EXCEPTION);
1512     CLEAR_PENDING_EXCEPTION;
1513     // JVMTI has already reported the pending exception
1514     // JVMTI internal flag reset is needed in order to report PrivilegedActionException
1515     if (THREAD->is_Java_thread()) {
1516       JvmtiExport::clear_detected_exception((JavaThread*) THREAD);
1517     }
1518     if ( pending_exception->is_a(SystemDictionary::Exception_klass()) &&
1519         !pending_exception->is_a(SystemDictionary::RuntimeException_klass())) {
1520       // Throw a java.security.PrivilegedActionException(Exception e) exception
1521       JavaCallArguments args(pending_exception);
1522       THROW_ARG_0(vmSymbols::java_security_PrivilegedActionException(),
1523                   vmSymbols::exception_void_signature(),
1524                   &args);
1525     }
1526   }
1527 
1528   if (pending_exception.not_null()) THROW_OOP_0(pending_exception());
1529   return JNIHandles::make_local(env, (oop) result.get_jobject());
1530 JVM_END
1531 
1532 
1533 // Returns the inherited_access_control_context field of the running thread.
1534 JVM_ENTRY(jobject, JVM_GetInheritedAccessControlContext(JNIEnv *env, jclass cls))
1535   JVMWrapper("JVM_GetInheritedAccessControlContext");
1536   oop result = java_lang_Thread::inherited_access_control_context(thread->threadObj());
1537   return JNIHandles::make_local(env, result);
1538 JVM_END
1539 
1540 class RegisterArrayForGC {
1541  private:
1542   JavaThread *_thread;
1543  public:
1544   RegisterArrayForGC(JavaThread *thread, GrowableArray<oop>* array)  {
1545     _thread = thread;
1546     _thread->register_array_for_gc(array);
1547   }
1548 
1549   ~RegisterArrayForGC() {
1550     _thread->register_array_for_gc(NULL);
1551   }
1552 };
1553 
1554 
1555 JVM_ENTRY(jobject, JVM_GetStackAccessControlContext(JNIEnv *env, jclass cls))
1556   JVMWrapper("JVM_GetStackAccessControlContext");
1557   if (!UsePrivilegedStack) return NULL;
1558 
1559   ResourceMark rm(THREAD);
1560   GrowableArray<oop>* local_array = new GrowableArray<oop>(12);
1561   JvmtiVMObjectAllocEventCollector oam;
1562 
1563   // count the protection domains on the execution stack. We collapse
1564   // duplicate consecutive protection domains into a single one, as
1565   // well as stopping when we hit a privileged frame.
1566 
1567   // Use vframeStream to iterate through Java frames
1568   vframeStream vfst(thread);
1569 
1570   oop previous_protection_domain = NULL;
1571   Handle privileged_context(thread, NULL);
1572   bool is_privileged = false;
1573   oop protection_domain = NULL;
1574 
1575   for(; !vfst.at_end(); vfst.next()) {
1576     // get method of frame
1577     Method* method = vfst.method();
1578     intptr_t* frame_id   = vfst.frame_id();
1579 
1580     // check the privileged frames to see if we have a match
1581     if (thread->privileged_stack_top() && thread->privileged_stack_top()->frame_id() == frame_id) {
1582       // this frame is privileged
1583       is_privileged = true;
1584       privileged_context = Handle(thread, thread->privileged_stack_top()->privileged_context());
1585       protection_domain  = thread->privileged_stack_top()->protection_domain();
1586     } else {
1587       protection_domain = method->method_holder()->protection_domain();
1588     }
1589 
1590     if ((previous_protection_domain != protection_domain) && (protection_domain != NULL)) {
1591       local_array->push(protection_domain);
1592       previous_protection_domain = protection_domain;
1593     }
1594 
1595     if (is_privileged) break;
1596   }
1597 
1598 
1599   // either all the domains on the stack were system domains, or
1600   // we had a privileged system domain
1601   if (local_array->is_empty()) {
1602     if (is_privileged && privileged_context.is_null()) return NULL;
1603 
1604     oop result = java_security_AccessControlContext::create(objArrayHandle(), is_privileged, privileged_context, CHECK_NULL);
1605     return JNIHandles::make_local(env, result);
1606   }
1607 
1608   // the resource area must be registered in case of a gc
1609   RegisterArrayForGC ragc(thread, local_array);
1610   objArrayOop context = oopFactory::new_objArray(SystemDictionary::ProtectionDomain_klass(),
1611                                                  local_array->length(), CHECK_NULL);
1612   objArrayHandle h_context(thread, context);
1613   for (int index = 0; index < local_array->length(); index++) {
1614     h_context->obj_at_put(index, local_array->at(index));
1615   }
1616 
1617   oop result = java_security_AccessControlContext::create(h_context, is_privileged, privileged_context, CHECK_NULL);
1618 
1619   return JNIHandles::make_local(env, result);
1620 JVM_END
1621 
1622 
1623 JVM_QUICK_ENTRY(jboolean, JVM_IsArrayClass(JNIEnv *env, jclass cls))
1624   JVMWrapper("JVM_IsArrayClass");
1625   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
1626   return (k != NULL) && k->oop_is_array() ? true : false;
1627 JVM_END
1628 
1629 
1630 JVM_QUICK_ENTRY(jboolean, JVM_IsPrimitiveClass(JNIEnv *env, jclass cls))
1631   JVMWrapper("JVM_IsPrimitiveClass");
1632   oop mirror = JNIHandles::resolve_non_null(cls);
1633   return (jboolean) java_lang_Class::is_primitive(mirror);
1634 JVM_END
1635 
1636 
1637 JVM_ENTRY(jclass, JVM_GetComponentType(JNIEnv *env, jclass cls))
1638   JVMWrapper("JVM_GetComponentType");
1639   oop mirror = JNIHandles::resolve_non_null(cls);
1640   oop result = Reflection::array_component_type(mirror, CHECK_NULL);
1641   return (jclass) JNIHandles::make_local(env, result);
1642 JVM_END
1643 
1644 
1645 JVM_ENTRY(jint, JVM_GetClassModifiers(JNIEnv *env, jclass cls))
1646   JVMWrapper("JVM_GetClassModifiers");
1647   if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(cls))) {
1648     // Primitive type
1649     return JVM_ACC_ABSTRACT | JVM_ACC_FINAL | JVM_ACC_PUBLIC;
1650   }
1651 
1652   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
1653   debug_only(int computed_modifiers = k->compute_modifier_flags(CHECK_0));
1654   assert(k->modifier_flags() == computed_modifiers, "modifiers cache is OK");
1655   return k->modifier_flags();
1656 JVM_END
1657 
1658 
1659 // Inner class reflection ///////////////////////////////////////////////////////////////////////////////
1660 
1661 JVM_ENTRY(jobjectArray, JVM_GetDeclaredClasses(JNIEnv *env, jclass ofClass))
1662   JvmtiVMObjectAllocEventCollector oam;
1663   // ofClass is a reference to a java_lang_Class object. The mirror object
1664   // of an InstanceKlass
1665 
1666   if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(ofClass)) ||
1667       ! java_lang_Class::as_Klass(JNIHandles::resolve_non_null(ofClass))->oop_is_instance()) {
1668     oop result = oopFactory::new_objArray(SystemDictionary::Class_klass(), 0, CHECK_NULL);
1669     return (jobjectArray)JNIHandles::make_local(env, result);
1670   }
1671 
1672   instanceKlassHandle k(thread, java_lang_Class::as_Klass(JNIHandles::resolve_non_null(ofClass)));
1673   InnerClassesIterator iter(k);
1674 
1675   if (iter.length() == 0) {
1676     // Neither an inner nor outer class
1677     oop result = oopFactory::new_objArray(SystemDictionary::Class_klass(), 0, CHECK_NULL);
1678     return (jobjectArray)JNIHandles::make_local(env, result);
1679   }
1680 
1681   // find inner class info
1682   constantPoolHandle cp(thread, k->constants());
1683   int length = iter.length();
1684 
1685   // Allocate temp. result array
1686   objArrayOop r = oopFactory::new_objArray(SystemDictionary::Class_klass(), length/4, CHECK_NULL);
1687   objArrayHandle result (THREAD, r);
1688   int members = 0;
1689 
1690   for (; !iter.done(); iter.next()) {
1691     int ioff = iter.inner_class_info_index();
1692     int ooff = iter.outer_class_info_index();
1693 
1694     if (ioff != 0 && ooff != 0) {
1695       // Check to see if the name matches the class we're looking for
1696       // before attempting to find the class.
1697       if (cp->klass_name_at_matches(k, ooff)) {
1698         Klass* outer_klass = cp->klass_at(ooff, CHECK_NULL);
1699         if (outer_klass == k()) {
1700            Klass* ik = cp->klass_at(ioff, CHECK_NULL);
1701            instanceKlassHandle inner_klass (THREAD, ik);
1702 
1703            // Throws an exception if outer klass has not declared k as
1704            // an inner klass
1705            Reflection::check_for_inner_class(k, inner_klass, true, CHECK_NULL);
1706 
1707            result->obj_at_put(members, inner_klass->java_mirror());
1708            members++;
1709         }
1710       }
1711     }
1712   }
1713 
1714   if (members != length) {
1715     // Return array of right length
1716     objArrayOop res = oopFactory::new_objArray(SystemDictionary::Class_klass(), members, CHECK_NULL);
1717     for(int i = 0; i < members; i++) {
1718       res->obj_at_put(i, result->obj_at(i));
1719     }
1720     return (jobjectArray)JNIHandles::make_local(env, res);
1721   }
1722 
1723   return (jobjectArray)JNIHandles::make_local(env, result());
1724 JVM_END
1725 
1726 
1727 JVM_ENTRY(jclass, JVM_GetDeclaringClass(JNIEnv *env, jclass ofClass))
1728 {
1729   // ofClass is a reference to a java_lang_Class object.
1730   if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(ofClass)) ||
1731       ! java_lang_Class::as_Klass(JNIHandles::resolve_non_null(ofClass))->oop_is_instance()) {
1732     return NULL;
1733   }
1734 
1735   bool inner_is_member = false;
1736   Klass* outer_klass
1737     = InstanceKlass::cast(java_lang_Class::as_Klass(JNIHandles::resolve_non_null(ofClass))
1738                           )->compute_enclosing_class(&inner_is_member, CHECK_NULL);
1739   if (outer_klass == NULL)  return NULL;  // already a top-level class
1740   if (!inner_is_member)  return NULL;     // an anonymous class (inside a method)
1741   return (jclass) JNIHandles::make_local(env, outer_klass->java_mirror());
1742 }
1743 JVM_END
1744 
1745 // should be in InstanceKlass.cpp, but is here for historical reasons
1746 Klass* InstanceKlass::compute_enclosing_class_impl(instanceKlassHandle k,
1747                                                      bool* inner_is_member,
1748                                                      TRAPS) {
1749   Thread* thread = THREAD;
1750   InnerClassesIterator iter(k);
1751   if (iter.length() == 0) {
1752     // No inner class info => no declaring class
1753     return NULL;
1754   }
1755 
1756   constantPoolHandle i_cp(thread, k->constants());
1757 
1758   bool found = false;
1759   Klass* ok;
1760   instanceKlassHandle outer_klass;
1761   *inner_is_member = false;
1762 
1763   // Find inner_klass attribute
1764   for (; !iter.done() && !found; iter.next()) {
1765     int ioff = iter.inner_class_info_index();
1766     int ooff = iter.outer_class_info_index();
1767     int noff = iter.inner_name_index();
1768     if (ioff != 0) {
1769       // Check to see if the name matches the class we're looking for
1770       // before attempting to find the class.
1771       if (i_cp->klass_name_at_matches(k, ioff)) {
1772         Klass* inner_klass = i_cp->klass_at(ioff, CHECK_NULL);
1773         found = (k() == inner_klass);
1774         if (found && ooff != 0) {
1775           ok = i_cp->klass_at(ooff, CHECK_NULL);
1776           if (!ok->oop_is_instance()) {
1777             // If the outer class is not an instance klass then it cannot have
1778             // declared any inner classes.
1779             ResourceMark rm(THREAD);
1780             Exceptions::fthrow(
1781               THREAD_AND_LOCATION,
1782               vmSymbols::java_lang_IncompatibleClassChangeError(),
1783               "%s and %s disagree on InnerClasses attribute",
1784               ok->external_name(),
1785               k->external_name());
1786             return NULL;
1787           }
1788           outer_klass = instanceKlassHandle(thread, ok);
1789           *inner_is_member = true;
1790         }
1791       }
1792     }
1793   }
1794 
1795   if (found && outer_klass.is_null()) {
1796     // It may be anonymous; try for that.
1797     int encl_method_class_idx = k->enclosing_method_class_index();
1798     if (encl_method_class_idx != 0) {
1799       ok = i_cp->klass_at(encl_method_class_idx, CHECK_NULL);
1800       outer_klass = instanceKlassHandle(thread, ok);
1801       *inner_is_member = false;
1802     }
1803   }
1804 
1805   // If no inner class attribute found for this class.
1806   if (outer_klass.is_null())  return NULL;
1807 
1808   // Throws an exception if outer klass has not declared k as an inner klass
1809   // We need evidence that each klass knows about the other, or else
1810   // the system could allow a spoof of an inner class to gain access rights.
1811   Reflection::check_for_inner_class(outer_klass, k, *inner_is_member, CHECK_NULL);
1812   return outer_klass();
1813 }
1814 
1815 JVM_ENTRY(jstring, JVM_GetClassSignature(JNIEnv *env, jclass cls))
1816   assert (cls != NULL, "illegal class");
1817   JVMWrapper("JVM_GetClassSignature");
1818   JvmtiVMObjectAllocEventCollector oam;
1819   ResourceMark rm(THREAD);
1820   // Return null for arrays and primatives
1821   if (!java_lang_Class::is_primitive(JNIHandles::resolve(cls))) {
1822     Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve(cls));
1823     if (k->oop_is_instance()) {
1824       Symbol* sym = InstanceKlass::cast(k)->generic_signature();
1825       if (sym == NULL) return NULL;
1826       Handle str = java_lang_String::create_from_symbol(sym, CHECK_NULL);
1827       return (jstring) JNIHandles::make_local(env, str());
1828     }
1829   }
1830   return NULL;
1831 JVM_END
1832 
1833 
1834 JVM_ENTRY(jbyteArray, JVM_GetClassAnnotations(JNIEnv *env, jclass cls))
1835   assert (cls != NULL, "illegal class");
1836   JVMWrapper("JVM_GetClassAnnotations");
1837 
1838   // Return null for arrays and primitives
1839   if (!java_lang_Class::is_primitive(JNIHandles::resolve(cls))) {
1840     Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve(cls));
1841     if (k->oop_is_instance()) {
1842       typeArrayOop a = Annotations::make_java_array(InstanceKlass::cast(k)->class_annotations(), CHECK_NULL);
1843       return (jbyteArray) JNIHandles::make_local(env, a);
1844     }
1845   }
1846   return NULL;
1847 JVM_END
1848 
1849 
1850 static bool jvm_get_field_common(jobject field, fieldDescriptor& fd, TRAPS) {
1851   // some of this code was adapted from from jni_FromReflectedField
1852 
1853   oop reflected = JNIHandles::resolve_non_null(field);
1854   oop mirror    = java_lang_reflect_Field::clazz(reflected);
1855   Klass* k    = java_lang_Class::as_Klass(mirror);
1856   int slot      = java_lang_reflect_Field::slot(reflected);
1857   int modifiers = java_lang_reflect_Field::modifiers(reflected);
1858 
1859   KlassHandle kh(THREAD, k);
1860   intptr_t offset = InstanceKlass::cast(kh())->field_offset(slot);
1861 
1862   if (modifiers & JVM_ACC_STATIC) {
1863     // for static fields we only look in the current class
1864     if (!InstanceKlass::cast(kh())->find_local_field_from_offset(offset, true, &fd)) {
1865       assert(false, "cannot find static field");
1866       return false;
1867     }
1868   } else {
1869     // for instance fields we start with the current class and work
1870     // our way up through the superclass chain
1871     if (!InstanceKlass::cast(kh())->find_field_from_offset(offset, false, &fd)) {
1872       assert(false, "cannot find instance field");
1873       return false;
1874     }
1875   }
1876   return true;
1877 }
1878 
1879 JVM_ENTRY(jbyteArray, JVM_GetFieldAnnotations(JNIEnv *env, jobject field))
1880   // field is a handle to a java.lang.reflect.Field object
1881   assert(field != NULL, "illegal field");
1882   JVMWrapper("JVM_GetFieldAnnotations");
1883 
1884   fieldDescriptor fd;
1885   bool gotFd = jvm_get_field_common(field, fd, CHECK_NULL);
1886   if (!gotFd) {
1887     return NULL;
1888   }
1889 
1890   return (jbyteArray) JNIHandles::make_local(env, Annotations::make_java_array(fd.annotations(), THREAD));
1891 JVM_END
1892 
1893 
1894 static Method* jvm_get_method_common(jobject method) {
1895   // some of this code was adapted from from jni_FromReflectedMethod
1896 
1897   oop reflected = JNIHandles::resolve_non_null(method);
1898   oop mirror    = NULL;
1899   int slot      = 0;
1900 
1901   if (reflected->klass() == SystemDictionary::reflect_Constructor_klass()) {
1902     mirror = java_lang_reflect_Constructor::clazz(reflected);
1903     slot   = java_lang_reflect_Constructor::slot(reflected);
1904   } else {
1905     assert(reflected->klass() == SystemDictionary::reflect_Method_klass(),
1906            "wrong type");
1907     mirror = java_lang_reflect_Method::clazz(reflected);
1908     slot   = java_lang_reflect_Method::slot(reflected);
1909   }
1910   Klass* k = java_lang_Class::as_Klass(mirror);
1911 
1912   Method* m = InstanceKlass::cast(k)->method_with_idnum(slot);
1913   assert(m != NULL, "cannot find method");
1914   return m;  // caller has to deal with NULL in product mode
1915 }
1916 
1917 
1918 JVM_ENTRY(jbyteArray, JVM_GetMethodAnnotations(JNIEnv *env, jobject method))
1919   JVMWrapper("JVM_GetMethodAnnotations");
1920 
1921   // method is a handle to a java.lang.reflect.Method object
1922   Method* m = jvm_get_method_common(method);
1923   if (m == NULL) {
1924     return NULL;
1925   }
1926 
1927   return (jbyteArray) JNIHandles::make_local(env,
1928     Annotations::make_java_array(m->annotations(), THREAD));
1929 JVM_END
1930 
1931 
1932 JVM_ENTRY(jbyteArray, JVM_GetMethodDefaultAnnotationValue(JNIEnv *env, jobject method))
1933   JVMWrapper("JVM_GetMethodDefaultAnnotationValue");
1934 
1935   // method is a handle to a java.lang.reflect.Method object
1936   Method* m = jvm_get_method_common(method);
1937   if (m == NULL) {
1938     return NULL;
1939   }
1940 
1941   return (jbyteArray) JNIHandles::make_local(env,
1942     Annotations::make_java_array(m->annotation_default(), THREAD));
1943 JVM_END
1944 
1945 
1946 JVM_ENTRY(jbyteArray, JVM_GetMethodParameterAnnotations(JNIEnv *env, jobject method))
1947   JVMWrapper("JVM_GetMethodParameterAnnotations");
1948 
1949   // method is a handle to a java.lang.reflect.Method object
1950   Method* m = jvm_get_method_common(method);
1951   if (m == NULL) {
1952     return NULL;
1953   }
1954 
1955   return (jbyteArray) JNIHandles::make_local(env,
1956     Annotations::make_java_array(m->parameter_annotations(), THREAD));
1957 JVM_END
1958 
1959 /* Type use annotations support (JDK 1.8) */
1960 
1961 JVM_ENTRY(jbyteArray, JVM_GetClassTypeAnnotations(JNIEnv *env, jclass cls))
1962   assert (cls != NULL, "illegal class");
1963   JVMWrapper("JVM_GetClassTypeAnnotations");
1964   ResourceMark rm(THREAD);
1965   // Return null for arrays and primitives
1966   if (!java_lang_Class::is_primitive(JNIHandles::resolve(cls))) {
1967     Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve(cls));
1968     if (k->oop_is_instance()) {
1969       AnnotationArray* type_annotations = InstanceKlass::cast(k)->class_type_annotations();
1970       if (type_annotations != NULL) {
1971         typeArrayOop a = Annotations::make_java_array(type_annotations, CHECK_NULL);
1972         return (jbyteArray) JNIHandles::make_local(env, a);
1973       }
1974     }
1975   }
1976   return NULL;
1977 JVM_END
1978 
1979 JVM_ENTRY(jbyteArray, JVM_GetMethodTypeAnnotations(JNIEnv *env, jobject method))
1980   assert (method != NULL, "illegal method");
1981   JVMWrapper("JVM_GetMethodTypeAnnotations");
1982 
1983   // method is a handle to a java.lang.reflect.Method object
1984   Method* m = jvm_get_method_common(method);
1985   if (m == NULL) {
1986     return NULL;
1987   }
1988 
1989   AnnotationArray* type_annotations = m->type_annotations();
1990   if (type_annotations != NULL) {
1991     typeArrayOop a = Annotations::make_java_array(type_annotations, CHECK_NULL);
1992     return (jbyteArray) JNIHandles::make_local(env, a);
1993   }
1994 
1995   return NULL;
1996 JVM_END
1997 
1998 JVM_ENTRY(jbyteArray, JVM_GetFieldTypeAnnotations(JNIEnv *env, jobject field))
1999   assert (field != NULL, "illegal field");
2000   JVMWrapper("JVM_GetFieldTypeAnnotations");
2001 
2002   fieldDescriptor fd;
2003   bool gotFd = jvm_get_field_common(field, fd, CHECK_NULL);
2004   if (!gotFd) {
2005     return NULL;
2006   }
2007 
2008   return (jbyteArray) JNIHandles::make_local(env, Annotations::make_java_array(fd.type_annotations(), THREAD));
2009 JVM_END
2010 
2011 static void bounds_check(constantPoolHandle cp, jint index, TRAPS) {
2012   if (!cp->is_within_bounds(index)) {
2013     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "Constant pool index out of bounds");
2014   }
2015 }
2016 
2017 JVM_ENTRY(jobjectArray, JVM_GetMethodParameters(JNIEnv *env, jobject method))
2018 {
2019   JVMWrapper("JVM_GetMethodParameters");
2020   // method is a handle to a java.lang.reflect.Method object
2021   Method* method_ptr = jvm_get_method_common(method);
2022   methodHandle mh (THREAD, method_ptr);
2023   Handle reflected_method (THREAD, JNIHandles::resolve_non_null(method));
2024   const int num_params = mh->method_parameters_length();
2025 
2026   if (0 != num_params) {
2027     // make sure all the symbols are properly formatted
2028     for (int i = 0; i < num_params; i++) {
2029       MethodParametersElement* params = mh->method_parameters_start();
2030       int index = params[i].name_cp_index;
2031       bounds_check(mh->constants(), index, CHECK_NULL);
2032 
2033       if (0 != index && !mh->constants()->tag_at(index).is_utf8()) {
2034         THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
2035                     "Wrong type at constant pool index");
2036       }
2037 
2038     }
2039 
2040     objArrayOop result_oop = oopFactory::new_objArray(SystemDictionary::reflect_Parameter_klass(), num_params, CHECK_NULL);
2041     objArrayHandle result (THREAD, result_oop);
2042 
2043     for (int i = 0; i < num_params; i++) {
2044       MethodParametersElement* params = mh->method_parameters_start();
2045       // For a 0 index, give a NULL symbol
2046       Symbol* sym = 0 != params[i].name_cp_index ?
2047         mh->constants()->symbol_at(params[i].name_cp_index) : NULL;
2048       int flags = params[i].flags;
2049       oop param = Reflection::new_parameter(reflected_method, i, sym,
2050                                             flags, CHECK_NULL);
2051       result->obj_at_put(i, param);
2052     }
2053     return (jobjectArray)JNIHandles::make_local(env, result());
2054   } else {
2055     return (jobjectArray)NULL;
2056   }
2057 }
2058 JVM_END
2059 
2060 // New (JDK 1.4) reflection implementation /////////////////////////////////////
2061 
2062 JVM_ENTRY(jobjectArray, JVM_GetClassDeclaredFields(JNIEnv *env, jclass ofClass, jboolean publicOnly))
2063 {
2064   JVMWrapper("JVM_GetClassDeclaredFields");
2065   JvmtiVMObjectAllocEventCollector oam;
2066 
2067   // Exclude primitive types and array types
2068   if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(ofClass)) ||
2069       java_lang_Class::as_Klass(JNIHandles::resolve_non_null(ofClass))->oop_is_array()) {
2070     // Return empty array
2071     oop res = oopFactory::new_objArray(SystemDictionary::reflect_Field_klass(), 0, CHECK_NULL);
2072     return (jobjectArray) JNIHandles::make_local(env, res);
2073   }
2074 
2075   instanceKlassHandle k(THREAD, java_lang_Class::as_Klass(JNIHandles::resolve_non_null(ofClass)));
2076   constantPoolHandle cp(THREAD, k->constants());
2077 
2078   // Ensure class is linked
2079   k->link_class(CHECK_NULL);
2080 
2081   // 4496456 We need to filter out java.lang.Throwable.backtrace
2082   bool skip_backtrace = false;
2083 
2084   // Allocate result
2085   int num_fields;
2086 
2087   if (publicOnly) {
2088     num_fields = 0;
2089     for (JavaFieldStream fs(k()); !fs.done(); fs.next()) {
2090       if (fs.access_flags().is_public()) ++num_fields;
2091     }
2092   } else {
2093     num_fields = k->java_fields_count();
2094 
2095     if (k() == SystemDictionary::Throwable_klass()) {
2096       num_fields--;
2097       skip_backtrace = true;
2098     }
2099   }
2100 
2101   objArrayOop r = oopFactory::new_objArray(SystemDictionary::reflect_Field_klass(), num_fields, CHECK_NULL);
2102   objArrayHandle result (THREAD, r);
2103 
2104   int out_idx = 0;
2105   fieldDescriptor fd;
2106   for (JavaFieldStream fs(k); !fs.done(); fs.next()) {
2107     if (skip_backtrace) {
2108       // 4496456 skip java.lang.Throwable.backtrace
2109       int offset = fs.offset();
2110       if (offset == java_lang_Throwable::get_backtrace_offset()) continue;
2111     }
2112 
2113     if (!publicOnly || fs.access_flags().is_public()) {
2114       fd.reinitialize(k(), fs.index());
2115       oop field = Reflection::new_field(&fd, UseNewReflection, CHECK_NULL);
2116       result->obj_at_put(out_idx, field);
2117       ++out_idx;
2118     }
2119   }
2120   assert(out_idx == num_fields, "just checking");
2121   return (jobjectArray) JNIHandles::make_local(env, result());
2122 }
2123 JVM_END
2124 
2125 static bool select_method(methodHandle method, bool want_constructor) {
2126   if (want_constructor) {
2127     return (method->is_initializer() && !method->is_static());
2128   } else {
2129     return  (!method->is_initializer() && !method->is_overpass());
2130   }
2131 }
2132 
2133 static jobjectArray get_class_declared_methods_helper(
2134                                   JNIEnv *env,
2135                                   jclass ofClass, jboolean publicOnly,
2136                                   bool want_constructor,
2137                                   Klass* klass, TRAPS) {
2138 
2139   JvmtiVMObjectAllocEventCollector oam;
2140 
2141   // Exclude primitive types and array types
2142   if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(ofClass))
2143       || java_lang_Class::as_Klass(JNIHandles::resolve_non_null(ofClass))->oop_is_array()) {
2144     // Return empty array
2145     oop res = oopFactory::new_objArray(klass, 0, CHECK_NULL);
2146     return (jobjectArray) JNIHandles::make_local(env, res);
2147   }
2148 
2149   instanceKlassHandle k(THREAD, java_lang_Class::as_Klass(JNIHandles::resolve_non_null(ofClass)));
2150 
2151   // Ensure class is linked
2152   k->link_class(CHECK_NULL);
2153 
2154   Array<Method*>* methods = k->methods();
2155   int methods_length = methods->length();
2156 
2157   // Save original method_idnum in case of redefinition, which can change
2158   // the idnum of obsolete methods.  The new method will have the same idnum
2159   // but if we refresh the methods array, the counts will be wrong.
2160   ResourceMark rm(THREAD);
2161   GrowableArray<int>* idnums = new GrowableArray<int>(methods_length);
2162   int num_methods = 0;
2163 
2164   for (int i = 0; i < methods_length; i++) {
2165     methodHandle method(THREAD, methods->at(i));
2166     if (select_method(method, want_constructor)) {
2167       if (!publicOnly || method->is_public()) {
2168         idnums->push(method->method_idnum());
2169         ++num_methods;
2170       }
2171     }
2172   }
2173 
2174   // Allocate result
2175   objArrayOop r = oopFactory::new_objArray(klass, num_methods, CHECK_NULL);
2176   objArrayHandle result (THREAD, r);
2177 
2178   // Now just put the methods that we selected above, but go by their idnum
2179   // in case of redefinition.  The methods can be redefined at any safepoint,
2180   // so above when allocating the oop array and below when creating reflect
2181   // objects.
2182   for (int i = 0; i < num_methods; i++) {
2183     methodHandle method(THREAD, k->method_with_idnum(idnums->at(i)));
2184     if (method.is_null()) {
2185       // Method may have been deleted and seems this API can handle null
2186       // Otherwise should probably put a method that throws NSME
2187       result->obj_at_put(i, NULL);
2188     } else {
2189       oop m;
2190       if (want_constructor) {
2191         m = Reflection::new_constructor(method, CHECK_NULL);
2192       } else {
2193         m = Reflection::new_method(method, UseNewReflection, false, CHECK_NULL);
2194       }
2195       result->obj_at_put(i, m);
2196     }
2197   }
2198 
2199   return (jobjectArray) JNIHandles::make_local(env, result());
2200 }
2201 
2202 JVM_ENTRY(jobjectArray, JVM_GetClassDeclaredMethods(JNIEnv *env, jclass ofClass, jboolean publicOnly))
2203 {
2204   JVMWrapper("JVM_GetClassDeclaredMethods");
2205   return get_class_declared_methods_helper(env, ofClass, publicOnly,
2206                                            /*want_constructor*/ false,
2207                                            SystemDictionary::reflect_Method_klass(), THREAD);
2208 }
2209 JVM_END
2210 
2211 JVM_ENTRY(jobjectArray, JVM_GetClassDeclaredConstructors(JNIEnv *env, jclass ofClass, jboolean publicOnly))
2212 {
2213   JVMWrapper("JVM_GetClassDeclaredConstructors");
2214   return get_class_declared_methods_helper(env, ofClass, publicOnly,
2215                                            /*want_constructor*/ true,
2216                                            SystemDictionary::reflect_Constructor_klass(), THREAD);
2217 }
2218 JVM_END
2219 
2220 JVM_ENTRY(jint, JVM_GetClassAccessFlags(JNIEnv *env, jclass cls))
2221 {
2222   JVMWrapper("JVM_GetClassAccessFlags");
2223   if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(cls))) {
2224     // Primitive type
2225     return JVM_ACC_ABSTRACT | JVM_ACC_FINAL | JVM_ACC_PUBLIC;
2226   }
2227 
2228   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2229   return k->access_flags().as_int() & JVM_ACC_WRITTEN_FLAGS;
2230 }
2231 JVM_END
2232 
2233 
2234 // Constant pool access //////////////////////////////////////////////////////////
2235 
2236 JVM_ENTRY(jobject, JVM_GetClassConstantPool(JNIEnv *env, jclass cls))
2237 {
2238   JVMWrapper("JVM_GetClassConstantPool");
2239   JvmtiVMObjectAllocEventCollector oam;
2240 
2241   // Return null for primitives and arrays
2242   if (!java_lang_Class::is_primitive(JNIHandles::resolve_non_null(cls))) {
2243     Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2244     if (k->oop_is_instance()) {
2245       instanceKlassHandle k_h(THREAD, k);
2246       Handle jcp = sun_reflect_ConstantPool::create(CHECK_NULL);
2247       sun_reflect_ConstantPool::set_cp(jcp(), k_h->constants());
2248       return JNIHandles::make_local(jcp());
2249     }
2250   }
2251   return NULL;
2252 }
2253 JVM_END
2254 
2255 
2256 JVM_ENTRY(jint, JVM_ConstantPoolGetSize(JNIEnv *env, jobject obj, jobject unused))
2257 {
2258   JVMWrapper("JVM_ConstantPoolGetSize");
2259   constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2260   return cp->length();
2261 }
2262 JVM_END
2263 
2264 
2265 JVM_ENTRY(jclass, JVM_ConstantPoolGetClassAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2266 {
2267   JVMWrapper("JVM_ConstantPoolGetClassAt");
2268   constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2269   bounds_check(cp, index, CHECK_NULL);
2270   constantTag tag = cp->tag_at(index);
2271   if (!tag.is_klass() && !tag.is_unresolved_klass()) {
2272     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2273   }
2274   Klass* k = cp->klass_at(index, CHECK_NULL);
2275   return (jclass) JNIHandles::make_local(k->java_mirror());
2276 }
2277 JVM_END
2278 
2279 JVM_ENTRY(jclass, JVM_ConstantPoolGetClassAtIfLoaded(JNIEnv *env, jobject obj, jobject unused, jint index))
2280 {
2281   JVMWrapper("JVM_ConstantPoolGetClassAtIfLoaded");
2282   constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2283   bounds_check(cp, index, CHECK_NULL);
2284   constantTag tag = cp->tag_at(index);
2285   if (!tag.is_klass() && !tag.is_unresolved_klass()) {
2286     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2287   }
2288   Klass* k = ConstantPool::klass_at_if_loaded(cp, index);
2289   if (k == NULL) return NULL;
2290   return (jclass) JNIHandles::make_local(k->java_mirror());
2291 }
2292 JVM_END
2293 
2294 static jobject get_method_at_helper(constantPoolHandle cp, jint index, bool force_resolution, TRAPS) {
2295   constantTag tag = cp->tag_at(index);
2296   if (!tag.is_method() && !tag.is_interface_method()) {
2297     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2298   }
2299   int klass_ref  = cp->uncached_klass_ref_index_at(index);
2300   Klass* k_o;
2301   if (force_resolution) {
2302     k_o = cp->klass_at(klass_ref, CHECK_NULL);
2303   } else {
2304     k_o = ConstantPool::klass_at_if_loaded(cp, klass_ref);
2305     if (k_o == NULL) return NULL;
2306   }
2307   instanceKlassHandle k(THREAD, k_o);
2308   Symbol* name = cp->uncached_name_ref_at(index);
2309   Symbol* sig  = cp->uncached_signature_ref_at(index);
2310   methodHandle m (THREAD, k->find_method(name, sig));
2311   if (m.is_null()) {
2312     THROW_MSG_0(vmSymbols::java_lang_RuntimeException(), "Unable to look up method in target class");
2313   }
2314   oop method;
2315   if (!m->is_initializer() || m->is_static()) {
2316     method = Reflection::new_method(m, true, true, CHECK_NULL);
2317   } else {
2318     method = Reflection::new_constructor(m, CHECK_NULL);
2319   }
2320   return JNIHandles::make_local(method);
2321 }
2322 
2323 JVM_ENTRY(jobject, JVM_ConstantPoolGetMethodAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2324 {
2325   JVMWrapper("JVM_ConstantPoolGetMethodAt");
2326   JvmtiVMObjectAllocEventCollector oam;
2327   constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2328   bounds_check(cp, index, CHECK_NULL);
2329   jobject res = get_method_at_helper(cp, index, true, CHECK_NULL);
2330   return res;
2331 }
2332 JVM_END
2333 
2334 JVM_ENTRY(jobject, JVM_ConstantPoolGetMethodAtIfLoaded(JNIEnv *env, jobject obj, jobject unused, jint index))
2335 {
2336   JVMWrapper("JVM_ConstantPoolGetMethodAtIfLoaded");
2337   JvmtiVMObjectAllocEventCollector oam;
2338   constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2339   bounds_check(cp, index, CHECK_NULL);
2340   jobject res = get_method_at_helper(cp, index, false, CHECK_NULL);
2341   return res;
2342 }
2343 JVM_END
2344 
2345 static jobject get_field_at_helper(constantPoolHandle cp, jint index, bool force_resolution, TRAPS) {
2346   constantTag tag = cp->tag_at(index);
2347   if (!tag.is_field()) {
2348     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2349   }
2350   int klass_ref  = cp->uncached_klass_ref_index_at(index);
2351   Klass* k_o;
2352   if (force_resolution) {
2353     k_o = cp->klass_at(klass_ref, CHECK_NULL);
2354   } else {
2355     k_o = ConstantPool::klass_at_if_loaded(cp, klass_ref);
2356     if (k_o == NULL) return NULL;
2357   }
2358   instanceKlassHandle k(THREAD, k_o);
2359   Symbol* name = cp->uncached_name_ref_at(index);
2360   Symbol* sig  = cp->uncached_signature_ref_at(index);
2361   fieldDescriptor fd;
2362   Klass* target_klass = k->find_field(name, sig, &fd);
2363   if (target_klass == NULL) {
2364     THROW_MSG_0(vmSymbols::java_lang_RuntimeException(), "Unable to look up field in target class");
2365   }
2366   oop field = Reflection::new_field(&fd, true, CHECK_NULL);
2367   return JNIHandles::make_local(field);
2368 }
2369 
2370 JVM_ENTRY(jobject, JVM_ConstantPoolGetFieldAt(JNIEnv *env, jobject obj, jobject unusedl, jint index))
2371 {
2372   JVMWrapper("JVM_ConstantPoolGetFieldAt");
2373   JvmtiVMObjectAllocEventCollector oam;
2374   constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2375   bounds_check(cp, index, CHECK_NULL);
2376   jobject res = get_field_at_helper(cp, index, true, CHECK_NULL);
2377   return res;
2378 }
2379 JVM_END
2380 
2381 JVM_ENTRY(jobject, JVM_ConstantPoolGetFieldAtIfLoaded(JNIEnv *env, jobject obj, jobject unused, jint index))
2382 {
2383   JVMWrapper("JVM_ConstantPoolGetFieldAtIfLoaded");
2384   JvmtiVMObjectAllocEventCollector oam;
2385   constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2386   bounds_check(cp, index, CHECK_NULL);
2387   jobject res = get_field_at_helper(cp, index, false, CHECK_NULL);
2388   return res;
2389 }
2390 JVM_END
2391 
2392 JVM_ENTRY(jobjectArray, JVM_ConstantPoolGetMemberRefInfoAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2393 {
2394   JVMWrapper("JVM_ConstantPoolGetMemberRefInfoAt");
2395   JvmtiVMObjectAllocEventCollector oam;
2396   constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2397   bounds_check(cp, index, CHECK_NULL);
2398   constantTag tag = cp->tag_at(index);
2399   if (!tag.is_field_or_method()) {
2400     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2401   }
2402   int klass_ref = cp->uncached_klass_ref_index_at(index);
2403   Symbol*  klass_name  = cp->klass_name_at(klass_ref);
2404   Symbol*  member_name = cp->uncached_name_ref_at(index);
2405   Symbol*  member_sig  = cp->uncached_signature_ref_at(index);
2406   objArrayOop  dest_o = oopFactory::new_objArray(SystemDictionary::String_klass(), 3, CHECK_NULL);
2407   objArrayHandle dest(THREAD, dest_o);
2408   Handle str = java_lang_String::create_from_symbol(klass_name, CHECK_NULL);
2409   dest->obj_at_put(0, str());
2410   str = java_lang_String::create_from_symbol(member_name, CHECK_NULL);
2411   dest->obj_at_put(1, str());
2412   str = java_lang_String::create_from_symbol(member_sig, CHECK_NULL);
2413   dest->obj_at_put(2, str());
2414   return (jobjectArray) JNIHandles::make_local(dest());
2415 }
2416 JVM_END
2417 
2418 JVM_ENTRY(jint, JVM_ConstantPoolGetIntAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2419 {
2420   JVMWrapper("JVM_ConstantPoolGetIntAt");
2421   constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2422   bounds_check(cp, index, CHECK_0);
2423   constantTag tag = cp->tag_at(index);
2424   if (!tag.is_int()) {
2425     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2426   }
2427   return cp->int_at(index);
2428 }
2429 JVM_END
2430 
2431 JVM_ENTRY(jlong, JVM_ConstantPoolGetLongAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2432 {
2433   JVMWrapper("JVM_ConstantPoolGetLongAt");
2434   constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2435   bounds_check(cp, index, CHECK_(0L));
2436   constantTag tag = cp->tag_at(index);
2437   if (!tag.is_long()) {
2438     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2439   }
2440   return cp->long_at(index);
2441 }
2442 JVM_END
2443 
2444 JVM_ENTRY(jfloat, JVM_ConstantPoolGetFloatAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2445 {
2446   JVMWrapper("JVM_ConstantPoolGetFloatAt");
2447   constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2448   bounds_check(cp, index, CHECK_(0.0f));
2449   constantTag tag = cp->tag_at(index);
2450   if (!tag.is_float()) {
2451     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2452   }
2453   return cp->float_at(index);
2454 }
2455 JVM_END
2456 
2457 JVM_ENTRY(jdouble, JVM_ConstantPoolGetDoubleAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2458 {
2459   JVMWrapper("JVM_ConstantPoolGetDoubleAt");
2460   constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2461   bounds_check(cp, index, CHECK_(0.0));
2462   constantTag tag = cp->tag_at(index);
2463   if (!tag.is_double()) {
2464     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2465   }
2466   return cp->double_at(index);
2467 }
2468 JVM_END
2469 
2470 JVM_ENTRY(jstring, JVM_ConstantPoolGetStringAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2471 {
2472   JVMWrapper("JVM_ConstantPoolGetStringAt");
2473   constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2474   bounds_check(cp, index, CHECK_NULL);
2475   constantTag tag = cp->tag_at(index);
2476   if (!tag.is_string()) {
2477     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2478   }
2479   oop str = cp->string_at(index, CHECK_NULL);
2480   return (jstring) JNIHandles::make_local(str);
2481 }
2482 JVM_END
2483 
2484 JVM_ENTRY(jstring, JVM_ConstantPoolGetUTF8At(JNIEnv *env, jobject obj, jobject unused, jint index))
2485 {
2486   JVMWrapper("JVM_ConstantPoolGetUTF8At");
2487   JvmtiVMObjectAllocEventCollector oam;
2488   constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2489   bounds_check(cp, index, CHECK_NULL);
2490   constantTag tag = cp->tag_at(index);
2491   if (!tag.is_symbol()) {
2492     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2493   }
2494   Symbol* sym = cp->symbol_at(index);
2495   Handle str = java_lang_String::create_from_symbol(sym, CHECK_NULL);
2496   return (jstring) JNIHandles::make_local(str());
2497 }
2498 JVM_END
2499 
2500 
2501 // Assertion support. //////////////////////////////////////////////////////////
2502 
2503 JVM_ENTRY(jboolean, JVM_DesiredAssertionStatus(JNIEnv *env, jclass unused, jclass cls))
2504   JVMWrapper("JVM_DesiredAssertionStatus");
2505   assert(cls != NULL, "bad class");
2506 
2507   oop r = JNIHandles::resolve(cls);
2508   assert(! java_lang_Class::is_primitive(r), "primitive classes not allowed");
2509   if (java_lang_Class::is_primitive(r)) return false;
2510 
2511   Klass* k = java_lang_Class::as_Klass(r);
2512   assert(k->oop_is_instance(), "must be an instance klass");
2513   if (! k->oop_is_instance()) return false;
2514 
2515   ResourceMark rm(THREAD);
2516   const char* name = k->name()->as_C_string();
2517   bool system_class = k->class_loader() == NULL;
2518   return JavaAssertions::enabled(name, system_class);
2519 
2520 JVM_END
2521 
2522 
2523 // Return a new AssertionStatusDirectives object with the fields filled in with
2524 // command-line assertion arguments (i.e., -ea, -da).
2525 JVM_ENTRY(jobject, JVM_AssertionStatusDirectives(JNIEnv *env, jclass unused))
2526   JVMWrapper("JVM_AssertionStatusDirectives");
2527   JvmtiVMObjectAllocEventCollector oam;
2528   oop asd = JavaAssertions::createAssertionStatusDirectives(CHECK_NULL);
2529   return JNIHandles::make_local(env, asd);
2530 JVM_END
2531 
2532 // Verification ////////////////////////////////////////////////////////////////////////////////
2533 
2534 // Reflection for the verifier /////////////////////////////////////////////////////////////////
2535 
2536 // RedefineClasses support: bug 6214132 caused verification to fail.
2537 // All functions from this section should call the jvmtiThreadSate function:
2538 //   Klass* class_to_verify_considering_redefinition(Klass* klass).
2539 // The function returns a Klass* of the _scratch_class if the verifier
2540 // was invoked in the middle of the class redefinition.
2541 // Otherwise it returns its argument value which is the _the_class Klass*.
2542 // Please, refer to the description in the jvmtiThreadSate.hpp.
2543 
2544 JVM_ENTRY(const char*, JVM_GetClassNameUTF(JNIEnv *env, jclass cls))
2545   JVMWrapper("JVM_GetClassNameUTF");
2546   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2547   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2548   return k->name()->as_utf8();
2549 JVM_END
2550 
2551 
2552 JVM_QUICK_ENTRY(void, JVM_GetClassCPTypes(JNIEnv *env, jclass cls, unsigned char *types))
2553   JVMWrapper("JVM_GetClassCPTypes");
2554   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2555   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2556   // types will have length zero if this is not an InstanceKlass
2557   // (length is determined by call to JVM_GetClassCPEntriesCount)
2558   if (k->oop_is_instance()) {
2559     ConstantPool* cp = InstanceKlass::cast(k)->constants();
2560     for (int index = cp->length() - 1; index >= 0; index--) {
2561       constantTag tag = cp->tag_at(index);
2562       types[index] = (tag.is_unresolved_klass()) ? JVM_CONSTANT_Class : tag.value();
2563   }
2564   }
2565 JVM_END
2566 
2567 
2568 JVM_QUICK_ENTRY(jint, JVM_GetClassCPEntriesCount(JNIEnv *env, jclass cls))
2569   JVMWrapper("JVM_GetClassCPEntriesCount");
2570   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2571   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2572   if (!k->oop_is_instance())
2573     return 0;
2574   return InstanceKlass::cast(k)->constants()->length();
2575 JVM_END
2576 
2577 
2578 JVM_QUICK_ENTRY(jint, JVM_GetClassFieldsCount(JNIEnv *env, jclass cls))
2579   JVMWrapper("JVM_GetClassFieldsCount");
2580   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2581   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2582   if (!k->oop_is_instance())
2583     return 0;
2584   return InstanceKlass::cast(k)->java_fields_count();
2585 JVM_END
2586 
2587 
2588 JVM_QUICK_ENTRY(jint, JVM_GetClassMethodsCount(JNIEnv *env, jclass cls))
2589   JVMWrapper("JVM_GetClassMethodsCount");
2590   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2591   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2592   if (!k->oop_is_instance())
2593     return 0;
2594   return InstanceKlass::cast(k)->methods()->length();
2595 JVM_END
2596 
2597 
2598 // The following methods, used for the verifier, are never called with
2599 // array klasses, so a direct cast to InstanceKlass is safe.
2600 // Typically, these methods are called in a loop with bounds determined
2601 // by the results of JVM_GetClass{Fields,Methods}Count, which return
2602 // zero for arrays.
2603 JVM_QUICK_ENTRY(void, JVM_GetMethodIxExceptionIndexes(JNIEnv *env, jclass cls, jint method_index, unsigned short *exceptions))
2604   JVMWrapper("JVM_GetMethodIxExceptionIndexes");
2605   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2606   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2607   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2608   int length = method->checked_exceptions_length();
2609   if (length > 0) {
2610     CheckedExceptionElement* table= method->checked_exceptions_start();
2611     for (int i = 0; i < length; i++) {
2612       exceptions[i] = table[i].class_cp_index;
2613     }
2614   }
2615 JVM_END
2616 
2617 
2618 JVM_QUICK_ENTRY(jint, JVM_GetMethodIxExceptionsCount(JNIEnv *env, jclass cls, jint method_index))
2619   JVMWrapper("JVM_GetMethodIxExceptionsCount");
2620   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2621   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2622   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2623   return method->checked_exceptions_length();
2624 JVM_END
2625 
2626 
2627 JVM_QUICK_ENTRY(void, JVM_GetMethodIxByteCode(JNIEnv *env, jclass cls, jint method_index, unsigned char *code))
2628   JVMWrapper("JVM_GetMethodIxByteCode");
2629   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2630   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2631   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2632   memcpy(code, method->code_base(), method->code_size());
2633 JVM_END
2634 
2635 
2636 JVM_QUICK_ENTRY(jint, JVM_GetMethodIxByteCodeLength(JNIEnv *env, jclass cls, jint method_index))
2637   JVMWrapper("JVM_GetMethodIxByteCodeLength");
2638   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2639   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2640   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2641   return method->code_size();
2642 JVM_END
2643 
2644 
2645 JVM_QUICK_ENTRY(void, JVM_GetMethodIxExceptionTableEntry(JNIEnv *env, jclass cls, jint method_index, jint entry_index, JVM_ExceptionTableEntryType *entry))
2646   JVMWrapper("JVM_GetMethodIxExceptionTableEntry");
2647   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2648   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2649   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2650   ExceptionTable extable(method);
2651   entry->start_pc   = extable.start_pc(entry_index);
2652   entry->end_pc     = extable.end_pc(entry_index);
2653   entry->handler_pc = extable.handler_pc(entry_index);
2654   entry->catchType  = extable.catch_type_index(entry_index);
2655 JVM_END
2656 
2657 
2658 JVM_QUICK_ENTRY(jint, JVM_GetMethodIxExceptionTableLength(JNIEnv *env, jclass cls, int method_index))
2659   JVMWrapper("JVM_GetMethodIxExceptionTableLength");
2660   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2661   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2662   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2663   return method->exception_table_length();
2664 JVM_END
2665 
2666 
2667 JVM_QUICK_ENTRY(jint, JVM_GetMethodIxModifiers(JNIEnv *env, jclass cls, int method_index))
2668   JVMWrapper("JVM_GetMethodIxModifiers");
2669   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2670   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2671   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2672   return method->access_flags().as_int() & JVM_RECOGNIZED_METHOD_MODIFIERS;
2673 JVM_END
2674 
2675 
2676 JVM_QUICK_ENTRY(jint, JVM_GetFieldIxModifiers(JNIEnv *env, jclass cls, int field_index))
2677   JVMWrapper("JVM_GetFieldIxModifiers");
2678   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2679   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2680   return InstanceKlass::cast(k)->field_access_flags(field_index) & JVM_RECOGNIZED_FIELD_MODIFIERS;
2681 JVM_END
2682 
2683 
2684 JVM_QUICK_ENTRY(jint, JVM_GetMethodIxLocalsCount(JNIEnv *env, jclass cls, int method_index))
2685   JVMWrapper("JVM_GetMethodIxLocalsCount");
2686   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2687   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2688   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2689   return method->max_locals();
2690 JVM_END
2691 
2692 
2693 JVM_QUICK_ENTRY(jint, JVM_GetMethodIxArgsSize(JNIEnv *env, jclass cls, int method_index))
2694   JVMWrapper("JVM_GetMethodIxArgsSize");
2695   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2696   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2697   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2698   return method->size_of_parameters();
2699 JVM_END
2700 
2701 
2702 JVM_QUICK_ENTRY(jint, JVM_GetMethodIxMaxStack(JNIEnv *env, jclass cls, int method_index))
2703   JVMWrapper("JVM_GetMethodIxMaxStack");
2704   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2705   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2706   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2707   return method->verifier_max_stack();
2708 JVM_END
2709 
2710 
2711 JVM_QUICK_ENTRY(jboolean, JVM_IsConstructorIx(JNIEnv *env, jclass cls, int method_index))
2712   JVMWrapper("JVM_IsConstructorIx");
2713   ResourceMark rm(THREAD);
2714   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2715   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2716   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2717   return method->name() == vmSymbols::object_initializer_name();
2718 JVM_END
2719 
2720 
2721 JVM_QUICK_ENTRY(jboolean, JVM_IsVMGeneratedMethodIx(JNIEnv *env, jclass cls, int method_index))
2722   JVMWrapper("JVM_IsVMGeneratedMethodIx");
2723   ResourceMark rm(THREAD);
2724   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2725   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2726   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2727   return method->is_overpass();
2728 JVM_END
2729 
2730 JVM_ENTRY(const char*, JVM_GetMethodIxNameUTF(JNIEnv *env, jclass cls, jint method_index))
2731   JVMWrapper("JVM_GetMethodIxIxUTF");
2732   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2733   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2734   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2735   return method->name()->as_utf8();
2736 JVM_END
2737 
2738 
2739 JVM_ENTRY(const char*, JVM_GetMethodIxSignatureUTF(JNIEnv *env, jclass cls, jint method_index))
2740   JVMWrapper("JVM_GetMethodIxSignatureUTF");
2741   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2742   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2743   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2744   return method->signature()->as_utf8();
2745 JVM_END
2746 
2747 /**
2748  * All of these JVM_GetCP-xxx methods are used by the old verifier to
2749  * read entries in the constant pool.  Since the old verifier always
2750  * works on a copy of the code, it will not see any rewriting that
2751  * may possibly occur in the middle of verification.  So it is important
2752  * that nothing it calls tries to use the cpCache instead of the raw
2753  * constant pool, so we must use cp->uncached_x methods when appropriate.
2754  */
2755 JVM_ENTRY(const char*, JVM_GetCPFieldNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2756   JVMWrapper("JVM_GetCPFieldNameUTF");
2757   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2758   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2759   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2760   switch (cp->tag_at(cp_index).value()) {
2761     case JVM_CONSTANT_Fieldref:
2762       return cp->uncached_name_ref_at(cp_index)->as_utf8();
2763     default:
2764       fatal("JVM_GetCPFieldNameUTF: illegal constant");
2765   }
2766   ShouldNotReachHere();
2767   return NULL;
2768 JVM_END
2769 
2770 
2771 JVM_ENTRY(const char*, JVM_GetCPMethodNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2772   JVMWrapper("JVM_GetCPMethodNameUTF");
2773   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2774   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2775   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2776   switch (cp->tag_at(cp_index).value()) {
2777     case JVM_CONSTANT_InterfaceMethodref:
2778     case JVM_CONSTANT_Methodref:
2779       return cp->uncached_name_ref_at(cp_index)->as_utf8();
2780     default:
2781       fatal("JVM_GetCPMethodNameUTF: illegal constant");
2782   }
2783   ShouldNotReachHere();
2784   return NULL;
2785 JVM_END
2786 
2787 
2788 JVM_ENTRY(const char*, JVM_GetCPMethodSignatureUTF(JNIEnv *env, jclass cls, jint cp_index))
2789   JVMWrapper("JVM_GetCPMethodSignatureUTF");
2790   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2791   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2792   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2793   switch (cp->tag_at(cp_index).value()) {
2794     case JVM_CONSTANT_InterfaceMethodref:
2795     case JVM_CONSTANT_Methodref:
2796       return cp->uncached_signature_ref_at(cp_index)->as_utf8();
2797     default:
2798       fatal("JVM_GetCPMethodSignatureUTF: illegal constant");
2799   }
2800   ShouldNotReachHere();
2801   return NULL;
2802 JVM_END
2803 
2804 
2805 JVM_ENTRY(const char*, JVM_GetCPFieldSignatureUTF(JNIEnv *env, jclass cls, jint cp_index))
2806   JVMWrapper("JVM_GetCPFieldSignatureUTF");
2807   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2808   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2809   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2810   switch (cp->tag_at(cp_index).value()) {
2811     case JVM_CONSTANT_Fieldref:
2812       return cp->uncached_signature_ref_at(cp_index)->as_utf8();
2813     default:
2814       fatal("JVM_GetCPFieldSignatureUTF: illegal constant");
2815   }
2816   ShouldNotReachHere();
2817   return NULL;
2818 JVM_END
2819 
2820 
2821 JVM_ENTRY(const char*, JVM_GetCPClassNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2822   JVMWrapper("JVM_GetCPClassNameUTF");
2823   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2824   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2825   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2826   Symbol* classname = cp->klass_name_at(cp_index);
2827   return classname->as_utf8();
2828 JVM_END
2829 
2830 
2831 JVM_ENTRY(const char*, JVM_GetCPFieldClassNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2832   JVMWrapper("JVM_GetCPFieldClassNameUTF");
2833   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2834   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2835   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2836   switch (cp->tag_at(cp_index).value()) {
2837     case JVM_CONSTANT_Fieldref: {
2838       int class_index = cp->uncached_klass_ref_index_at(cp_index);
2839       Symbol* classname = cp->klass_name_at(class_index);
2840       return classname->as_utf8();
2841     }
2842     default:
2843       fatal("JVM_GetCPFieldClassNameUTF: illegal constant");
2844   }
2845   ShouldNotReachHere();
2846   return NULL;
2847 JVM_END
2848 
2849 
2850 JVM_ENTRY(const char*, JVM_GetCPMethodClassNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2851   JVMWrapper("JVM_GetCPMethodClassNameUTF");
2852   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2853   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2854   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2855   switch (cp->tag_at(cp_index).value()) {
2856     case JVM_CONSTANT_Methodref:
2857     case JVM_CONSTANT_InterfaceMethodref: {
2858       int class_index = cp->uncached_klass_ref_index_at(cp_index);
2859       Symbol* classname = cp->klass_name_at(class_index);
2860       return classname->as_utf8();
2861     }
2862     default:
2863       fatal("JVM_GetCPMethodClassNameUTF: illegal constant");
2864   }
2865   ShouldNotReachHere();
2866   return NULL;
2867 JVM_END
2868 
2869 
2870 JVM_ENTRY(jint, JVM_GetCPFieldModifiers(JNIEnv *env, jclass cls, int cp_index, jclass called_cls))
2871   JVMWrapper("JVM_GetCPFieldModifiers");
2872   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2873   Klass* k_called = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(called_cls));
2874   k        = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2875   k_called = JvmtiThreadState::class_to_verify_considering_redefinition(k_called, thread);
2876   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2877   ConstantPool* cp_called = InstanceKlass::cast(k_called)->constants();
2878   switch (cp->tag_at(cp_index).value()) {
2879     case JVM_CONSTANT_Fieldref: {
2880       Symbol* name      = cp->uncached_name_ref_at(cp_index);
2881       Symbol* signature = cp->uncached_signature_ref_at(cp_index);
2882       for (JavaFieldStream fs(k_called); !fs.done(); fs.next()) {
2883         if (fs.name() == name && fs.signature() == signature) {
2884           return fs.access_flags().as_short() & JVM_RECOGNIZED_FIELD_MODIFIERS;
2885         }
2886       }
2887       return -1;
2888     }
2889     default:
2890       fatal("JVM_GetCPFieldModifiers: illegal constant");
2891   }
2892   ShouldNotReachHere();
2893   return 0;
2894 JVM_END
2895 
2896 
2897 JVM_QUICK_ENTRY(jint, JVM_GetCPMethodModifiers(JNIEnv *env, jclass cls, int cp_index, jclass called_cls))
2898   JVMWrapper("JVM_GetCPMethodModifiers");
2899   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2900   Klass* k_called = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(called_cls));
2901   k        = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2902   k_called = JvmtiThreadState::class_to_verify_considering_redefinition(k_called, thread);
2903   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2904   switch (cp->tag_at(cp_index).value()) {
2905     case JVM_CONSTANT_Methodref:
2906     case JVM_CONSTANT_InterfaceMethodref: {
2907       Symbol* name      = cp->uncached_name_ref_at(cp_index);
2908       Symbol* signature = cp->uncached_signature_ref_at(cp_index);
2909       Array<Method*>* methods = InstanceKlass::cast(k_called)->methods();
2910       int methods_count = methods->length();
2911       for (int i = 0; i < methods_count; i++) {
2912         Method* method = methods->at(i);
2913         if (method->name() == name && method->signature() == signature) {
2914             return method->access_flags().as_int() & JVM_RECOGNIZED_METHOD_MODIFIERS;
2915         }
2916       }
2917       return -1;
2918     }
2919     default:
2920       fatal("JVM_GetCPMethodModifiers: illegal constant");
2921   }
2922   ShouldNotReachHere();
2923   return 0;
2924 JVM_END
2925 
2926 
2927 // Misc //////////////////////////////////////////////////////////////////////////////////////////////
2928 
2929 JVM_LEAF(void, JVM_ReleaseUTF(const char *utf))
2930   // So long as UTF8::convert_to_utf8 returns resource strings, we don't have to do anything
2931 JVM_END
2932 
2933 
2934 JVM_ENTRY(jboolean, JVM_IsSameClassPackage(JNIEnv *env, jclass class1, jclass class2))
2935   JVMWrapper("JVM_IsSameClassPackage");
2936   oop class1_mirror = JNIHandles::resolve_non_null(class1);
2937   oop class2_mirror = JNIHandles::resolve_non_null(class2);
2938   Klass* klass1 = java_lang_Class::as_Klass(class1_mirror);
2939   Klass* klass2 = java_lang_Class::as_Klass(class2_mirror);
2940   return (jboolean) Reflection::is_same_class_package(klass1, klass2);
2941 JVM_END
2942 
2943 
2944 // IO functions ////////////////////////////////////////////////////////////////////////////////////////
2945 
2946 JVM_LEAF(jint, JVM_Open(const char *fname, jint flags, jint mode))
2947   JVMWrapper2("JVM_Open (%s)", fname);
2948 
2949   //%note jvm_r6
2950   int result = os::open(fname, flags, mode);
2951   if (result >= 0) {
2952     return result;
2953   } else {
2954     switch(errno) {
2955       case EEXIST:
2956         return JVM_EEXIST;
2957       default:
2958         return -1;
2959     }
2960   }
2961 JVM_END
2962 
2963 
2964 JVM_LEAF(jint, JVM_Close(jint fd))
2965   JVMWrapper2("JVM_Close (0x%x)", fd);
2966   //%note jvm_r6
2967   return os::close(fd);
2968 JVM_END
2969 
2970 
2971 JVM_LEAF(jint, JVM_Read(jint fd, char *buf, jint nbytes))
2972   JVMWrapper2("JVM_Read (0x%x)", fd);
2973 
2974   //%note jvm_r6
2975   return (jint)os::restartable_read(fd, buf, nbytes);
2976 JVM_END
2977 
2978 
2979 JVM_LEAF(jint, JVM_Write(jint fd, char *buf, jint nbytes))
2980   JVMWrapper2("JVM_Write (0x%x)", fd);
2981 
2982   //%note jvm_r6
2983   return (jint)os::write(fd, buf, nbytes);
2984 JVM_END
2985 
2986 
2987 JVM_LEAF(jint, JVM_Available(jint fd, jlong *pbytes))
2988   JVMWrapper2("JVM_Available (0x%x)", fd);
2989   //%note jvm_r6
2990   return os::available(fd, pbytes);
2991 JVM_END
2992 
2993 
2994 JVM_LEAF(jlong, JVM_Lseek(jint fd, jlong offset, jint whence))
2995   JVMWrapper4("JVM_Lseek (0x%x, " INT64_FORMAT ", %d)", fd, (int64_t) offset, whence);
2996   //%note jvm_r6
2997   return os::lseek(fd, offset, whence);
2998 JVM_END
2999 
3000 
3001 JVM_LEAF(jint, JVM_SetLength(jint fd, jlong length))
3002   JVMWrapper3("JVM_SetLength (0x%x, " INT64_FORMAT ")", fd, (int64_t) length);
3003   return os::ftruncate(fd, length);
3004 JVM_END
3005 
3006 
3007 JVM_LEAF(jint, JVM_Sync(jint fd))
3008   JVMWrapper2("JVM_Sync (0x%x)", fd);
3009   //%note jvm_r6
3010   return os::fsync(fd);
3011 JVM_END
3012 
3013 
3014 // Printing support //////////////////////////////////////////////////
3015 extern "C" {
3016 
3017 ATTRIBUTE_PRINTF(3, 0)
3018 int jio_vsnprintf(char *str, size_t count, const char *fmt, va_list args) {
3019   // Reject count values that are negative signed values converted to
3020   // unsigned; see bug 4399518, 4417214
3021   if ((intptr_t)count <= 0) return -1;
3022 
3023   int result = os::vsnprintf(str, count, fmt, args);
3024   if (result > 0 && (size_t)result >= count) {
3025     result = -1;
3026   }
3027 
3028   return result;
3029 }
3030 
3031 ATTRIBUTE_PRINTF(3, 0)
3032 int jio_snprintf(char *str, size_t count, const char *fmt, ...) {
3033   va_list args;
3034   int len;
3035   va_start(args, fmt);
3036   len = jio_vsnprintf(str, count, fmt, args);
3037   va_end(args);
3038   return len;
3039 }
3040 
3041 ATTRIBUTE_PRINTF(2,3)
3042 int jio_fprintf(FILE* f, const char *fmt, ...) {
3043   int len;
3044   va_list args;
3045   va_start(args, fmt);
3046   len = jio_vfprintf(f, fmt, args);
3047   va_end(args);
3048   return len;
3049 }
3050 
3051 ATTRIBUTE_PRINTF(2, 0)
3052 int jio_vfprintf(FILE* f, const char *fmt, va_list args) {
3053   if (Arguments::vfprintf_hook() != NULL) {
3054      return Arguments::vfprintf_hook()(f, fmt, args);
3055   } else {
3056     return vfprintf(f, fmt, args);
3057   }
3058 }
3059 
3060 ATTRIBUTE_PRINTF(1, 2)
3061 JNIEXPORT int jio_printf(const char *fmt, ...) {
3062   int len;
3063   va_list args;
3064   va_start(args, fmt);
3065   len = jio_vfprintf(defaultStream::output_stream(), fmt, args);
3066   va_end(args);
3067   return len;
3068 }
3069 
3070 
3071 // HotSpot specific jio method
3072 void jio_print(const char* s) {
3073   // Try to make this function as atomic as possible.
3074   if (Arguments::vfprintf_hook() != NULL) {
3075     jio_fprintf(defaultStream::output_stream(), "%s", s);
3076   } else {
3077     // Make an unused local variable to avoid warning from gcc 4.x compiler.
3078     size_t count = ::write(defaultStream::output_fd(), s, (int)strlen(s));
3079   }
3080 }
3081 
3082 } // Extern C
3083 
3084 // java.lang.Thread //////////////////////////////////////////////////////////////////////////////
3085 
3086 // In most of the JVM Thread support functions we need to be sure to lock the Threads_lock
3087 // to prevent the target thread from exiting after we have a pointer to the C++ Thread or
3088 // OSThread objects.  The exception to this rule is when the target object is the thread
3089 // doing the operation, in which case we know that the thread won't exit until the
3090 // operation is done (all exits being voluntary).  There are a few cases where it is
3091 // rather silly to do operations on yourself, like resuming yourself or asking whether
3092 // you are alive.  While these can still happen, they are not subject to deadlocks if
3093 // the lock is held while the operation occurs (this is not the case for suspend, for
3094 // instance), and are very unlikely.  Because IsAlive needs to be fast and its
3095 // implementation is local to this file, we always lock Threads_lock for that one.
3096 
3097 static void thread_entry(JavaThread* thread, TRAPS) {
3098   HandleMark hm(THREAD);
3099   Handle obj(THREAD, thread->threadObj());
3100   JavaValue result(T_VOID);
3101   JavaCalls::call_virtual(&result,
3102                           obj,
3103                           KlassHandle(THREAD, SystemDictionary::Thread_klass()),
3104                           vmSymbols::run_method_name(),
3105                           vmSymbols::void_method_signature(),
3106                           THREAD);
3107 }
3108 
3109 
3110 JVM_ENTRY(void, JVM_StartThread(JNIEnv* env, jobject jthread))
3111   JVMWrapper("JVM_StartThread");
3112   JavaThread *native_thread = NULL;
3113 
3114   // We cannot hold the Threads_lock when we throw an exception,
3115   // due to rank ordering issues. Example:  we might need to grab the
3116   // Heap_lock while we construct the exception.
3117   bool throw_illegal_thread_state = false;
3118 
3119   // We must release the Threads_lock before we can post a jvmti event
3120   // in Thread::start.
3121   {
3122     // Ensure that the C++ Thread and OSThread structures aren't freed before
3123     // we operate.
3124     MutexLocker mu(Threads_lock);
3125 
3126     // Since JDK 5 the java.lang.Thread threadStatus is used to prevent
3127     // re-starting an already started thread, so we should usually find
3128     // that the JavaThread is null. However for a JNI attached thread
3129     // there is a small window between the Thread object being created
3130     // (with its JavaThread set) and the update to its threadStatus, so we
3131     // have to check for this
3132     if (java_lang_Thread::thread(JNIHandles::resolve_non_null(jthread)) != NULL) {
3133       throw_illegal_thread_state = true;
3134     } else {
3135       // We could also check the stillborn flag to see if this thread was already stopped, but
3136       // for historical reasons we let the thread detect that itself when it starts running
3137 
3138       jlong size =
3139              java_lang_Thread::stackSize(JNIHandles::resolve_non_null(jthread));
3140       // Allocate the C++ Thread structure and create the native thread.  The
3141       // stack size retrieved from java is signed, but the constructor takes
3142       // size_t (an unsigned type), so avoid passing negative values which would
3143       // result in really large stacks.
3144       size_t sz = size > 0 ? (size_t) size : 0;
3145       native_thread = new JavaThread(&thread_entry, sz);
3146 
3147       // At this point it may be possible that no osthread was created for the
3148       // JavaThread due to lack of memory. Check for this situation and throw
3149       // an exception if necessary. Eventually we may want to change this so
3150       // that we only grab the lock if the thread was created successfully -
3151       // then we can also do this check and throw the exception in the
3152       // JavaThread constructor.
3153       if (native_thread->osthread() != NULL) {
3154         // Note: the current thread is not being used within "prepare".
3155         native_thread->prepare(jthread);
3156       }
3157     }
3158   }
3159 
3160   if (throw_illegal_thread_state) {
3161     THROW(vmSymbols::java_lang_IllegalThreadStateException());
3162   }
3163 
3164   assert(native_thread != NULL, "Starting null thread?");
3165 
3166   if (native_thread->osthread() == NULL) {
3167     // No one should hold a reference to the 'native_thread'.
3168     delete native_thread;
3169     if (JvmtiExport::should_post_resource_exhausted()) {
3170       JvmtiExport::post_resource_exhausted(
3171         JVMTI_RESOURCE_EXHAUSTED_OOM_ERROR | JVMTI_RESOURCE_EXHAUSTED_THREADS,
3172         "unable to create new native thread");
3173     }
3174     THROW_MSG(vmSymbols::java_lang_OutOfMemoryError(),
3175               "unable to create new native thread");
3176   }
3177 
3178 #if INCLUDE_JFR
3179   if (JfrRecorder::is_recording() && EventThreadStart::is_enabled() &&
3180       EventThreadStart::is_stacktrace_enabled()) {
3181     JfrThreadLocal* tl = native_thread->jfr_thread_local();
3182     // skip Thread.start() and Thread.start0()
3183     tl->set_cached_stack_trace_id(JfrStackTraceRepository::record(thread, 2));
3184   }
3185 #endif
3186 
3187   Thread::start(native_thread);
3188 
3189 JVM_END
3190 
3191 // JVM_Stop is implemented using a VM_Operation, so threads are forced to safepoints
3192 // before the quasi-asynchronous exception is delivered.  This is a little obtrusive,
3193 // but is thought to be reliable and simple. In the case, where the receiver is the
3194 // same thread as the sender, no safepoint is needed.
3195 JVM_ENTRY(void, JVM_StopThread(JNIEnv* env, jobject jthread, jobject throwable))
3196   JVMWrapper("JVM_StopThread");
3197 
3198   oop java_throwable = JNIHandles::resolve(throwable);
3199   if (java_throwable == NULL) {
3200     THROW(vmSymbols::java_lang_NullPointerException());
3201   }
3202   oop java_thread = JNIHandles::resolve_non_null(jthread);
3203   JavaThread* receiver = java_lang_Thread::thread(java_thread);
3204   Events::log_exception(JavaThread::current(),
3205                         "JVM_StopThread thread JavaThread " INTPTR_FORMAT " as oop " INTPTR_FORMAT " [exception " INTPTR_FORMAT "]",
3206                         p2i(receiver), p2i((address)java_thread), p2i(throwable));
3207   // First check if thread is alive
3208   if (receiver != NULL) {
3209     // Check if exception is getting thrown at self (use oop equality, since the
3210     // target object might exit)
3211     if (java_thread == thread->threadObj()) {
3212       THROW_OOP(java_throwable);
3213     } else {
3214       // Enques a VM_Operation to stop all threads and then deliver the exception...
3215       Thread::send_async_exception(java_thread, JNIHandles::resolve(throwable));
3216     }
3217   }
3218   else {
3219     // Either:
3220     // - target thread has not been started before being stopped, or
3221     // - target thread already terminated
3222     // We could read the threadStatus to determine which case it is
3223     // but that is overkill as it doesn't matter. We must set the
3224     // stillborn flag for the first case, and if the thread has already
3225     // exited setting this flag has no affect
3226     java_lang_Thread::set_stillborn(java_thread);
3227   }
3228 JVM_END
3229 
3230 
3231 JVM_ENTRY(jboolean, JVM_IsThreadAlive(JNIEnv* env, jobject jthread))
3232   JVMWrapper("JVM_IsThreadAlive");
3233 
3234   oop thread_oop = JNIHandles::resolve_non_null(jthread);
3235   return java_lang_Thread::is_alive(thread_oop);
3236 JVM_END
3237 
3238 
3239 JVM_ENTRY(void, JVM_SuspendThread(JNIEnv* env, jobject jthread))
3240   JVMWrapper("JVM_SuspendThread");
3241   oop java_thread = JNIHandles::resolve_non_null(jthread);
3242   JavaThread* receiver = java_lang_Thread::thread(java_thread);
3243 
3244   if (receiver != NULL) {
3245     // thread has run and has not exited (still on threads list)
3246 
3247     {
3248       MutexLockerEx ml(receiver->SR_lock(), Mutex::_no_safepoint_check_flag);
3249       if (receiver->is_external_suspend()) {
3250         // Don't allow nested external suspend requests. We can't return
3251         // an error from this interface so just ignore the problem.
3252         return;
3253       }
3254       if (receiver->is_exiting()) { // thread is in the process of exiting
3255         return;
3256       }
3257       receiver->set_external_suspend();
3258     }
3259 
3260     // java_suspend() will catch threads in the process of exiting
3261     // and will ignore them.
3262     receiver->java_suspend();
3263 
3264     // It would be nice to have the following assertion in all the
3265     // time, but it is possible for a racing resume request to have
3266     // resumed this thread right after we suspended it. Temporarily
3267     // enable this assertion if you are chasing a different kind of
3268     // bug.
3269     //
3270     // assert(java_lang_Thread::thread(receiver->threadObj()) == NULL ||
3271     //   receiver->is_being_ext_suspended(), "thread is not suspended");
3272   }
3273 JVM_END
3274 
3275 
3276 JVM_ENTRY(void, JVM_ResumeThread(JNIEnv* env, jobject jthread))
3277   JVMWrapper("JVM_ResumeThread");
3278   // Ensure that the C++ Thread and OSThread structures aren't freed before we operate.
3279   // We need to *always* get the threads lock here, since this operation cannot be allowed during
3280   // a safepoint. The safepoint code relies on suspending a thread to examine its state. If other
3281   // threads randomly resumes threads, then a thread might not be suspended when the safepoint code
3282   // looks at it.
3283   MutexLocker ml(Threads_lock);
3284   JavaThread* thr = java_lang_Thread::thread(JNIHandles::resolve_non_null(jthread));
3285   if (thr != NULL) {
3286     // the thread has run and is not in the process of exiting
3287     thr->java_resume();
3288   }
3289 JVM_END
3290 
3291 
3292 JVM_ENTRY(void, JVM_SetThreadPriority(JNIEnv* env, jobject jthread, jint prio))
3293   JVMWrapper("JVM_SetThreadPriority");
3294   // Ensure that the C++ Thread and OSThread structures aren't freed before we operate
3295   MutexLocker ml(Threads_lock);
3296   oop java_thread = JNIHandles::resolve_non_null(jthread);
3297   java_lang_Thread::set_priority(java_thread, (ThreadPriority)prio);
3298   JavaThread* thr = java_lang_Thread::thread(java_thread);
3299   if (thr != NULL) {                  // Thread not yet started; priority pushed down when it is
3300     Thread::set_priority(thr, (ThreadPriority)prio);
3301   }
3302 JVM_END
3303 
3304 
3305 JVM_ENTRY(void, JVM_Yield(JNIEnv *env, jclass threadClass))
3306   JVMWrapper("JVM_Yield");
3307   if (os::dont_yield()) return;
3308 #ifndef USDT2
3309   HS_DTRACE_PROBE0(hotspot, thread__yield);
3310 #else /* USDT2 */
3311   HOTSPOT_THREAD_YIELD();
3312 #endif /* USDT2 */
3313   // When ConvertYieldToSleep is off (default), this matches the classic VM use of yield.
3314   // Critical for similar threading behaviour
3315   if (ConvertYieldToSleep) {
3316     os::sleep(thread, MinSleepInterval, false);
3317   } else {
3318     os::yield();
3319   }
3320 JVM_END
3321 
3322 static void post_thread_sleep_event(EventThreadSleep* event, jlong millis) {
3323   assert(event != NULL, "invariant");
3324   assert(event->should_commit(), "invariant");
3325   event->set_time(millis);
3326   event->commit();
3327 }
3328 
3329 JVM_ENTRY(void, JVM_Sleep(JNIEnv* env, jclass threadClass, jlong millis))
3330   JVMWrapper("JVM_Sleep");
3331 
3332   if (millis < 0) {
3333     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "timeout value is negative");
3334   }
3335 
3336   if (Thread::is_interrupted (THREAD, true) && !HAS_PENDING_EXCEPTION) {
3337     THROW_MSG(vmSymbols::java_lang_InterruptedException(), "sleep interrupted");
3338   }
3339 
3340   // Save current thread state and restore it at the end of this block.
3341   // And set new thread state to SLEEPING.
3342   JavaThreadSleepState jtss(thread);
3343 
3344 #ifndef USDT2
3345   HS_DTRACE_PROBE1(hotspot, thread__sleep__begin, millis);
3346 #else /* USDT2 */
3347   HOTSPOT_THREAD_SLEEP_BEGIN(
3348                              millis);
3349 #endif /* USDT2 */
3350 
3351   EventThreadSleep event;
3352 
3353   if (millis == 0) {
3354     // When ConvertSleepToYield is on, this matches the classic VM implementation of
3355     // JVM_Sleep. Critical for similar threading behaviour (Win32)
3356     // It appears that in certain GUI contexts, it may be beneficial to do a short sleep
3357     // for SOLARIS
3358     if (ConvertSleepToYield) {
3359       os::yield();
3360     } else {
3361       ThreadState old_state = thread->osthread()->get_state();
3362       thread->osthread()->set_state(SLEEPING);
3363       os::sleep(thread, MinSleepInterval, false);
3364       thread->osthread()->set_state(old_state);
3365     }
3366   } else {
3367     ThreadState old_state = thread->osthread()->get_state();
3368     thread->osthread()->set_state(SLEEPING);
3369     if (os::sleep(thread, millis, true) == OS_INTRPT) {
3370       // An asynchronous exception (e.g., ThreadDeathException) could have been thrown on
3371       // us while we were sleeping. We do not overwrite those.
3372       if (!HAS_PENDING_EXCEPTION) {
3373         if (event.should_commit()) {
3374           post_thread_sleep_event(&event, millis);
3375         }
3376 #ifndef USDT2
3377         HS_DTRACE_PROBE1(hotspot, thread__sleep__end,1);
3378 #else /* USDT2 */
3379         HOTSPOT_THREAD_SLEEP_END(
3380                                  1);
3381 #endif /* USDT2 */
3382         // TODO-FIXME: THROW_MSG returns which means we will not call set_state()
3383         // to properly restore the thread state.  That's likely wrong.
3384         THROW_MSG(vmSymbols::java_lang_InterruptedException(), "sleep interrupted");
3385       }
3386     }
3387     thread->osthread()->set_state(old_state);
3388   }
3389   if (event.should_commit()) {
3390     post_thread_sleep_event(&event, millis);
3391   }
3392 #ifndef USDT2
3393   HS_DTRACE_PROBE1(hotspot, thread__sleep__end,0);
3394 #else /* USDT2 */
3395   HOTSPOT_THREAD_SLEEP_END(
3396                            0);
3397 #endif /* USDT2 */
3398 JVM_END
3399 
3400 JVM_ENTRY(jobject, JVM_CurrentThread(JNIEnv* env, jclass threadClass))
3401   JVMWrapper("JVM_CurrentThread");
3402   oop jthread = thread->threadObj();
3403   assert (thread != NULL, "no current thread!");
3404   return JNIHandles::make_local(env, jthread);
3405 JVM_END
3406 
3407 
3408 JVM_ENTRY(jint, JVM_CountStackFrames(JNIEnv* env, jobject jthread))
3409   JVMWrapper("JVM_CountStackFrames");
3410 
3411   // Ensure that the C++ Thread and OSThread structures aren't freed before we operate
3412   oop java_thread = JNIHandles::resolve_non_null(jthread);
3413   bool throw_illegal_thread_state = false;
3414   int count = 0;
3415 
3416   {
3417     MutexLockerEx ml(thread->threadObj() == java_thread ? NULL : Threads_lock);
3418     // We need to re-resolve the java_thread, since a GC might have happened during the
3419     // acquire of the lock
3420     JavaThread* thr = java_lang_Thread::thread(JNIHandles::resolve_non_null(jthread));
3421 
3422     if (thr == NULL) {
3423       // do nothing
3424     } else if(! thr->is_external_suspend() || ! thr->frame_anchor()->walkable()) {
3425       // Check whether this java thread has been suspended already. If not, throws
3426       // IllegalThreadStateException. We defer to throw that exception until
3427       // Threads_lock is released since loading exception class has to leave VM.
3428       // The correct way to test a thread is actually suspended is
3429       // wait_for_ext_suspend_completion(), but we can't call that while holding
3430       // the Threads_lock. The above tests are sufficient for our purposes
3431       // provided the walkability of the stack is stable - which it isn't
3432       // 100% but close enough for most practical purposes.
3433       throw_illegal_thread_state = true;
3434     } else {
3435       // Count all java activation, i.e., number of vframes
3436       for(vframeStream vfst(thr); !vfst.at_end(); vfst.next()) {
3437         // Native frames are not counted
3438         if (!vfst.method()->is_native()) count++;
3439        }
3440     }
3441   }
3442 
3443   if (throw_illegal_thread_state) {
3444     THROW_MSG_0(vmSymbols::java_lang_IllegalThreadStateException(),
3445                 "this thread is not suspended");
3446   }
3447   return count;
3448 JVM_END
3449 
3450 // Consider: A better way to implement JVM_Interrupt() is to acquire
3451 // Threads_lock to resolve the jthread into a Thread pointer, fetch
3452 // Thread->platformevent, Thread->native_thr, Thread->parker, etc.,
3453 // drop Threads_lock, and the perform the unpark() and thr_kill() operations
3454 // outside the critical section.  Threads_lock is hot so we want to minimize
3455 // the hold-time.  A cleaner interface would be to decompose interrupt into
3456 // two steps.  The 1st phase, performed under Threads_lock, would return
3457 // a closure that'd be invoked after Threads_lock was dropped.
3458 // This tactic is safe as PlatformEvent and Parkers are type-stable (TSM) and
3459 // admit spurious wakeups.
3460 
3461 JVM_ENTRY(void, JVM_Interrupt(JNIEnv* env, jobject jthread))
3462   JVMWrapper("JVM_Interrupt");
3463 
3464   // Ensure that the C++ Thread and OSThread structures aren't freed before we operate
3465   oop java_thread = JNIHandles::resolve_non_null(jthread);
3466   MutexLockerEx ml(thread->threadObj() == java_thread ? NULL : Threads_lock);
3467   // We need to re-resolve the java_thread, since a GC might have happened during the
3468   // acquire of the lock
3469   JavaThread* thr = java_lang_Thread::thread(JNIHandles::resolve_non_null(jthread));
3470   if (thr != NULL) {
3471     Thread::interrupt(thr);
3472   }
3473 JVM_END
3474 
3475 
3476 JVM_QUICK_ENTRY(jboolean, JVM_IsInterrupted(JNIEnv* env, jobject jthread, jboolean clear_interrupted))
3477   JVMWrapper("JVM_IsInterrupted");
3478 
3479   // Ensure that the C++ Thread and OSThread structures aren't freed before we operate
3480   oop java_thread = JNIHandles::resolve_non_null(jthread);
3481   MutexLockerEx ml(thread->threadObj() == java_thread ? NULL : Threads_lock);
3482   // We need to re-resolve the java_thread, since a GC might have happened during the
3483   // acquire of the lock
3484   JavaThread* thr = java_lang_Thread::thread(JNIHandles::resolve_non_null(jthread));
3485   if (thr == NULL) {
3486     return JNI_FALSE;
3487   } else {
3488     return (jboolean) Thread::is_interrupted(thr, clear_interrupted != 0);
3489   }
3490 JVM_END
3491 
3492 
3493 // Return true iff the current thread has locked the object passed in
3494 
3495 JVM_ENTRY(jboolean, JVM_HoldsLock(JNIEnv* env, jclass threadClass, jobject obj))
3496   JVMWrapper("JVM_HoldsLock");
3497   assert(THREAD->is_Java_thread(), "sanity check");
3498   if (obj == NULL) {
3499     THROW_(vmSymbols::java_lang_NullPointerException(), JNI_FALSE);
3500   }
3501   Handle h_obj(THREAD, JNIHandles::resolve(obj));
3502   return ObjectSynchronizer::current_thread_holds_lock((JavaThread*)THREAD, h_obj);
3503 JVM_END
3504 
3505 
3506 JVM_ENTRY(void, JVM_DumpAllStacks(JNIEnv* env, jclass))
3507   JVMWrapper("JVM_DumpAllStacks");
3508   VM_PrintThreads op;
3509   VMThread::execute(&op);
3510   if (JvmtiExport::should_post_data_dump()) {
3511     JvmtiExport::post_data_dump();
3512   }
3513 JVM_END
3514 
3515 JVM_ENTRY(void, JVM_SetNativeThreadName(JNIEnv* env, jobject jthread, jstring name))
3516   JVMWrapper("JVM_SetNativeThreadName");
3517   ResourceMark rm(THREAD);
3518   oop java_thread = JNIHandles::resolve_non_null(jthread);
3519   JavaThread* thr = java_lang_Thread::thread(java_thread);
3520   // Thread naming only supported for the current thread, doesn't work for
3521   // target threads.
3522   if (Thread::current() == thr && !thr->has_attached_via_jni()) {
3523     // we don't set the name of an attached thread to avoid stepping
3524     // on other programs
3525     const char *thread_name = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(name));
3526     os::set_native_thread_name(thread_name);
3527   }
3528 JVM_END
3529 
3530 // java.lang.SecurityManager ///////////////////////////////////////////////////////////////////////
3531 
3532 static bool is_trusted_frame(JavaThread* jthread, vframeStream* vfst) {
3533   assert(jthread->is_Java_thread(), "must be a Java thread");
3534   if (jthread->privileged_stack_top() == NULL) return false;
3535   if (jthread->privileged_stack_top()->frame_id() == vfst->frame_id()) {
3536     oop loader = jthread->privileged_stack_top()->class_loader();
3537     if (loader == NULL) return true;
3538     bool trusted = java_lang_ClassLoader::is_trusted_loader(loader);
3539     if (trusted) return true;
3540   }
3541   return false;
3542 }
3543 
3544 JVM_ENTRY(jclass, JVM_CurrentLoadedClass(JNIEnv *env))
3545   JVMWrapper("JVM_CurrentLoadedClass");
3546   ResourceMark rm(THREAD);
3547 
3548   for (vframeStream vfst(thread); !vfst.at_end(); vfst.next()) {
3549     // if a method in a class in a trusted loader is in a doPrivileged, return NULL
3550     bool trusted = is_trusted_frame(thread, &vfst);
3551     if (trusted) return NULL;
3552 
3553     Method* m = vfst.method();
3554     if (!m->is_native()) {
3555       InstanceKlass* holder = m->method_holder();
3556       oop loader = holder->class_loader();
3557       if (loader != NULL && !java_lang_ClassLoader::is_trusted_loader(loader)) {
3558         return (jclass) JNIHandles::make_local(env, holder->java_mirror());
3559       }
3560     }
3561   }
3562   return NULL;
3563 JVM_END
3564 
3565 
3566 JVM_ENTRY(jobject, JVM_CurrentClassLoader(JNIEnv *env))
3567   JVMWrapper("JVM_CurrentClassLoader");
3568   ResourceMark rm(THREAD);
3569 
3570   for (vframeStream vfst(thread); !vfst.at_end(); vfst.next()) {
3571 
3572     // if a method in a class in a trusted loader is in a doPrivileged, return NULL
3573     bool trusted = is_trusted_frame(thread, &vfst);
3574     if (trusted) return NULL;
3575 
3576     Method* m = vfst.method();
3577     if (!m->is_native()) {
3578       InstanceKlass* holder = m->method_holder();
3579       assert(holder->is_klass(), "just checking");
3580       oop loader = holder->class_loader();
3581       if (loader != NULL && !java_lang_ClassLoader::is_trusted_loader(loader)) {
3582         return JNIHandles::make_local(env, loader);
3583       }
3584     }
3585   }
3586   return NULL;
3587 JVM_END
3588 
3589 
3590 JVM_ENTRY(jobjectArray, JVM_GetClassContext(JNIEnv *env))
3591   JVMWrapper("JVM_GetClassContext");
3592   ResourceMark rm(THREAD);
3593   JvmtiVMObjectAllocEventCollector oam;
3594   vframeStream vfst(thread);
3595 
3596   if (SystemDictionary::reflect_CallerSensitive_klass() != NULL) {
3597     // This must only be called from SecurityManager.getClassContext
3598     Method* m = vfst.method();
3599     if (!(m->method_holder() == SystemDictionary::SecurityManager_klass() &&
3600           m->name()          == vmSymbols::getClassContext_name() &&
3601           m->signature()     == vmSymbols::void_class_array_signature())) {
3602       THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), "JVM_GetClassContext must only be called from SecurityManager.getClassContext");
3603     }
3604   }
3605 
3606   // Collect method holders
3607   GrowableArray<KlassHandle>* klass_array = new GrowableArray<KlassHandle>();
3608   for (; !vfst.at_end(); vfst.security_next()) {
3609     Method* m = vfst.method();
3610     // Native frames are not returned
3611     if (!m->is_ignored_by_security_stack_walk() && !m->is_native()) {
3612       Klass* holder = m->method_holder();
3613       assert(holder->is_klass(), "just checking");
3614       klass_array->append(holder);
3615     }
3616   }
3617 
3618   // Create result array of type [Ljava/lang/Class;
3619   objArrayOop result = oopFactory::new_objArray(SystemDictionary::Class_klass(), klass_array->length(), CHECK_NULL);
3620   // Fill in mirrors corresponding to method holders
3621   for (int i = 0; i < klass_array->length(); i++) {
3622     result->obj_at_put(i, klass_array->at(i)->java_mirror());
3623   }
3624 
3625   return (jobjectArray) JNIHandles::make_local(env, result);
3626 JVM_END
3627 
3628 
3629 JVM_ENTRY(jint, JVM_ClassDepth(JNIEnv *env, jstring name))
3630   JVMWrapper("JVM_ClassDepth");
3631   ResourceMark rm(THREAD);
3632   Handle h_name (THREAD, JNIHandles::resolve_non_null(name));
3633   Handle class_name_str = java_lang_String::internalize_classname(h_name, CHECK_0);
3634 
3635   const char* str = java_lang_String::as_utf8_string(class_name_str());
3636   TempNewSymbol class_name_sym = SymbolTable::probe(str, (int)strlen(str));
3637   if (class_name_sym == NULL) {
3638     return -1;
3639   }
3640 
3641   int depth = 0;
3642 
3643   for(vframeStream vfst(thread); !vfst.at_end(); vfst.next()) {
3644     if (!vfst.method()->is_native()) {
3645       InstanceKlass* holder = vfst.method()->method_holder();
3646       assert(holder->is_klass(), "just checking");
3647       if (holder->name() == class_name_sym) {
3648         return depth;
3649       }
3650       depth++;
3651     }
3652   }
3653   return -1;
3654 JVM_END
3655 
3656 
3657 JVM_ENTRY(jint, JVM_ClassLoaderDepth(JNIEnv *env))
3658   JVMWrapper("JVM_ClassLoaderDepth");
3659   ResourceMark rm(THREAD);
3660   int depth = 0;
3661   for (vframeStream vfst(thread); !vfst.at_end(); vfst.next()) {
3662     // if a method in a class in a trusted loader is in a doPrivileged, return -1
3663     bool trusted = is_trusted_frame(thread, &vfst);
3664     if (trusted) return -1;
3665 
3666     Method* m = vfst.method();
3667     if (!m->is_native()) {
3668       InstanceKlass* holder = m->method_holder();
3669       assert(holder->is_klass(), "just checking");
3670       oop loader = holder->class_loader();
3671       if (loader != NULL && !java_lang_ClassLoader::is_trusted_loader(loader)) {
3672         return depth;
3673       }
3674       depth++;
3675     }
3676   }
3677   return -1;
3678 JVM_END
3679 
3680 
3681 // java.lang.Package ////////////////////////////////////////////////////////////////
3682 
3683 
3684 JVM_ENTRY(jstring, JVM_GetSystemPackage(JNIEnv *env, jstring name))
3685   JVMWrapper("JVM_GetSystemPackage");
3686   ResourceMark rm(THREAD);
3687   JvmtiVMObjectAllocEventCollector oam;
3688   char* str = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(name));
3689   oop result = ClassLoader::get_system_package(str, CHECK_NULL);
3690   return (jstring) JNIHandles::make_local(result);
3691 JVM_END
3692 
3693 
3694 JVM_ENTRY(jobjectArray, JVM_GetSystemPackages(JNIEnv *env))
3695   JVMWrapper("JVM_GetSystemPackages");
3696   JvmtiVMObjectAllocEventCollector oam;
3697   objArrayOop result = ClassLoader::get_system_packages(CHECK_NULL);
3698   return (jobjectArray) JNIHandles::make_local(result);
3699 JVM_END
3700 
3701 
3702 // ObjectInputStream ///////////////////////////////////////////////////////////////
3703 
3704 bool force_verify_field_access(Klass* current_class, Klass* field_class, AccessFlags access, bool classloader_only) {
3705   if (current_class == NULL) {
3706     return true;
3707   }
3708   if ((current_class == field_class) || access.is_public()) {
3709     return true;
3710   }
3711 
3712   if (access.is_protected()) {
3713     // See if current_class is a subclass of field_class
3714     if (current_class->is_subclass_of(field_class)) {
3715       return true;
3716     }
3717   }
3718 
3719   return (!access.is_private() && InstanceKlass::cast(current_class)->is_same_class_package(field_class));
3720 }
3721 
3722 
3723 // JVM_AllocateNewObject and JVM_AllocateNewArray are unused as of 1.4
3724 JVM_ENTRY(jobject, JVM_AllocateNewObject(JNIEnv *env, jobject receiver, jclass currClass, jclass initClass))
3725   JVMWrapper("JVM_AllocateNewObject");
3726   JvmtiVMObjectAllocEventCollector oam;
3727   // Receiver is not used
3728   oop curr_mirror = JNIHandles::resolve_non_null(currClass);
3729   oop init_mirror = JNIHandles::resolve_non_null(initClass);
3730 
3731   // Cannot instantiate primitive types
3732   if (java_lang_Class::is_primitive(curr_mirror) || java_lang_Class::is_primitive(init_mirror)) {
3733     ResourceMark rm(THREAD);
3734     THROW_0(vmSymbols::java_lang_InvalidClassException());
3735   }
3736 
3737   // Arrays not allowed here, must use JVM_AllocateNewArray
3738   if (java_lang_Class::as_Klass(curr_mirror)->oop_is_array() ||
3739       java_lang_Class::as_Klass(init_mirror)->oop_is_array()) {
3740     ResourceMark rm(THREAD);
3741     THROW_0(vmSymbols::java_lang_InvalidClassException());
3742   }
3743 
3744   instanceKlassHandle curr_klass (THREAD, java_lang_Class::as_Klass(curr_mirror));
3745   instanceKlassHandle init_klass (THREAD, java_lang_Class::as_Klass(init_mirror));
3746 
3747   assert(curr_klass->is_subclass_of(init_klass()), "just checking");
3748 
3749   // Interfaces, abstract classes, and java.lang.Class classes cannot be instantiated directly.
3750   curr_klass->check_valid_for_instantiation(false, CHECK_NULL);
3751 
3752   // Make sure klass is initialized, since we are about to instantiate one of them.
3753   curr_klass->initialize(CHECK_NULL);
3754 
3755  methodHandle m (THREAD,
3756                  init_klass->find_method(vmSymbols::object_initializer_name(),
3757                                          vmSymbols::void_method_signature()));
3758   if (m.is_null()) {
3759     ResourceMark rm(THREAD);
3760     THROW_MSG_0(vmSymbols::java_lang_NoSuchMethodError(),
3761                 Method::name_and_sig_as_C_string(init_klass(),
3762                                           vmSymbols::object_initializer_name(),
3763                                           vmSymbols::void_method_signature()));
3764   }
3765 
3766   if (curr_klass ==  init_klass && !m->is_public()) {
3767     // Calling the constructor for class 'curr_klass'.
3768     // Only allow calls to a public no-arg constructor.
3769     // This path corresponds to creating an Externalizable object.
3770     THROW_0(vmSymbols::java_lang_IllegalAccessException());
3771   }
3772 
3773   if (!force_verify_field_access(curr_klass(), init_klass(), m->access_flags(), false)) {
3774     // subclass 'curr_klass' does not have access to no-arg constructor of 'initcb'
3775     THROW_0(vmSymbols::java_lang_IllegalAccessException());
3776   }
3777 
3778   Handle obj = curr_klass->allocate_instance_handle(CHECK_NULL);
3779   // Call constructor m. This might call a constructor higher up in the hierachy
3780   JavaCalls::call_default_constructor(thread, m, obj, CHECK_NULL);
3781 
3782   return JNIHandles::make_local(obj());
3783 JVM_END
3784 
3785 
3786 JVM_ENTRY(jobject, JVM_AllocateNewArray(JNIEnv *env, jobject obj, jclass currClass, jint length))
3787   JVMWrapper("JVM_AllocateNewArray");
3788   JvmtiVMObjectAllocEventCollector oam;
3789   oop mirror = JNIHandles::resolve_non_null(currClass);
3790 
3791   if (java_lang_Class::is_primitive(mirror)) {
3792     THROW_0(vmSymbols::java_lang_InvalidClassException());
3793   }
3794   Klass* k = java_lang_Class::as_Klass(mirror);
3795   oop result;
3796 
3797   if (k->oop_is_typeArray()) {
3798     // typeArray
3799     result = TypeArrayKlass::cast(k)->allocate(length, CHECK_NULL);
3800   } else if (k->oop_is_objArray()) {
3801     // objArray
3802     ObjArrayKlass* oak = ObjArrayKlass::cast(k);
3803     oak->initialize(CHECK_NULL); // make sure class is initialized (matches Classic VM behavior)
3804     result = oak->allocate(length, CHECK_NULL);
3805   } else {
3806     THROW_0(vmSymbols::java_lang_InvalidClassException());
3807   }
3808   return JNIHandles::make_local(env, result);
3809 JVM_END
3810 
3811 
3812 // Returns first non-privileged class loader on the stack (excluding reflection
3813 // generated frames) or null if only classes loaded by the boot class loader
3814 // and extension class loader are found on the stack.
3815 
3816 JVM_ENTRY(jobject, JVM_LatestUserDefinedLoader(JNIEnv *env))
3817   for (vframeStream vfst(thread); !vfst.at_end(); vfst.next()) {
3818     // UseNewReflection
3819     vfst.skip_reflection_related_frames(); // Only needed for 1.4 reflection
3820     oop loader = vfst.method()->method_holder()->class_loader();
3821     if (loader != NULL && !SystemDictionary::is_ext_class_loader(loader)) {
3822       return JNIHandles::make_local(env, loader);
3823     }
3824   }
3825   return NULL;
3826 JVM_END
3827 
3828 
3829 // Load a class relative to the most recent class on the stack  with a non-null
3830 // classloader.
3831 // This function has been deprecated and should not be considered part of the
3832 // specified JVM interface.
3833 
3834 JVM_ENTRY(jclass, JVM_LoadClass0(JNIEnv *env, jobject receiver,
3835                                  jclass currClass, jstring currClassName))
3836   JVMWrapper("JVM_LoadClass0");
3837   // Receiver is not used
3838   ResourceMark rm(THREAD);
3839 
3840   // Class name argument is not guaranteed to be in internal format
3841   Handle classname (THREAD, JNIHandles::resolve_non_null(currClassName));
3842   Handle string = java_lang_String::internalize_classname(classname, CHECK_NULL);
3843 
3844   const char* str = java_lang_String::as_utf8_string(string());
3845 
3846   if (str == NULL || (int)strlen(str) > Symbol::max_length()) {
3847     // It's impossible to create this class;  the name cannot fit
3848     // into the constant pool.
3849     THROW_MSG_0(vmSymbols::java_lang_NoClassDefFoundError(), str);
3850   }
3851 
3852   TempNewSymbol name = SymbolTable::new_symbol(str, CHECK_NULL);
3853   Handle curr_klass (THREAD, JNIHandles::resolve(currClass));
3854   // Find the most recent class on the stack with a non-null classloader
3855   oop loader = NULL;
3856   oop protection_domain = NULL;
3857   if (curr_klass.is_null()) {
3858     for (vframeStream vfst(thread);
3859          !vfst.at_end() && loader == NULL;
3860          vfst.next()) {
3861       if (!vfst.method()->is_native()) {
3862         InstanceKlass* holder = vfst.method()->method_holder();
3863         loader             = holder->class_loader();
3864         protection_domain  = holder->protection_domain();
3865       }
3866     }
3867   } else {
3868     Klass* curr_klass_oop = java_lang_Class::as_Klass(curr_klass());
3869     loader            = InstanceKlass::cast(curr_klass_oop)->class_loader();
3870     protection_domain = InstanceKlass::cast(curr_klass_oop)->protection_domain();
3871   }
3872   Handle h_loader(THREAD, loader);
3873   Handle h_prot  (THREAD, protection_domain);
3874   jclass result =  find_class_from_class_loader(env, name, true, h_loader, h_prot,
3875                                                 false, thread);
3876   if (TraceClassResolution && result != NULL) {
3877     trace_class_resolution(java_lang_Class::as_Klass(JNIHandles::resolve_non_null(result)));
3878   }
3879   return result;
3880 JVM_END
3881 
3882 
3883 // Array ///////////////////////////////////////////////////////////////////////////////////////////
3884 
3885 
3886 // resolve array handle and check arguments
3887 static inline arrayOop check_array(JNIEnv *env, jobject arr, bool type_array_only, TRAPS) {
3888   if (arr == NULL) {
3889     THROW_0(vmSymbols::java_lang_NullPointerException());
3890   }
3891   oop a = JNIHandles::resolve_non_null(arr);
3892   if (!a->is_array() || (type_array_only && !a->is_typeArray())) {
3893     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Argument is not an array");
3894   }
3895   return arrayOop(a);
3896 }
3897 
3898 
3899 JVM_ENTRY(jint, JVM_GetArrayLength(JNIEnv *env, jobject arr))
3900   JVMWrapper("JVM_GetArrayLength");
3901   arrayOop a = check_array(env, arr, false, CHECK_0);
3902   return a->length();
3903 JVM_END
3904 
3905 
3906 JVM_ENTRY(jobject, JVM_GetArrayElement(JNIEnv *env, jobject arr, jint index))
3907   JVMWrapper("JVM_Array_Get");
3908   JvmtiVMObjectAllocEventCollector oam;
3909   arrayOop a = check_array(env, arr, false, CHECK_NULL);
3910   jvalue value;
3911   BasicType type = Reflection::array_get(&value, a, index, CHECK_NULL);
3912   oop box = Reflection::box(&value, type, CHECK_NULL);
3913   return JNIHandles::make_local(env, box);
3914 JVM_END
3915 
3916 
3917 JVM_ENTRY(jvalue, JVM_GetPrimitiveArrayElement(JNIEnv *env, jobject arr, jint index, jint wCode))
3918   JVMWrapper("JVM_GetPrimitiveArrayElement");
3919   jvalue value;
3920   value.i = 0; // to initialize value before getting used in CHECK
3921   arrayOop a = check_array(env, arr, true, CHECK_(value));
3922   assert(a->is_typeArray(), "just checking");
3923   BasicType type = Reflection::array_get(&value, a, index, CHECK_(value));
3924   BasicType wide_type = (BasicType) wCode;
3925   if (type != wide_type) {
3926     Reflection::widen(&value, type, wide_type, CHECK_(value));
3927   }
3928   return value;
3929 JVM_END
3930 
3931 
3932 JVM_ENTRY(void, JVM_SetArrayElement(JNIEnv *env, jobject arr, jint index, jobject val))
3933   JVMWrapper("JVM_SetArrayElement");
3934   arrayOop a = check_array(env, arr, false, CHECK);
3935   oop box = JNIHandles::resolve(val);
3936   jvalue value;
3937   value.i = 0; // to initialize value before getting used in CHECK
3938   BasicType value_type;
3939   if (a->is_objArray()) {
3940     // Make sure we do no unbox e.g. java/lang/Integer instances when storing into an object array
3941     value_type = Reflection::unbox_for_regular_object(box, &value);
3942   } else {
3943     value_type = Reflection::unbox_for_primitive(box, &value, CHECK);
3944   }
3945   Reflection::array_set(&value, a, index, value_type, CHECK);
3946 JVM_END
3947 
3948 
3949 JVM_ENTRY(void, JVM_SetPrimitiveArrayElement(JNIEnv *env, jobject arr, jint index, jvalue v, unsigned char vCode))
3950   JVMWrapper("JVM_SetPrimitiveArrayElement");
3951   arrayOop a = check_array(env, arr, true, CHECK);
3952   assert(a->is_typeArray(), "just checking");
3953   BasicType value_type = (BasicType) vCode;
3954   Reflection::array_set(&v, a, index, value_type, CHECK);
3955 JVM_END
3956 
3957 
3958 JVM_ENTRY(jobject, JVM_NewArray(JNIEnv *env, jclass eltClass, jint length))
3959   JVMWrapper("JVM_NewArray");
3960   JvmtiVMObjectAllocEventCollector oam;
3961   oop element_mirror = JNIHandles::resolve(eltClass);
3962   oop result = Reflection::reflect_new_array(element_mirror, length, CHECK_NULL);
3963   return JNIHandles::make_local(env, result);
3964 JVM_END
3965 
3966 
3967 JVM_ENTRY(jobject, JVM_NewMultiArray(JNIEnv *env, jclass eltClass, jintArray dim))
3968   JVMWrapper("JVM_NewMultiArray");
3969   JvmtiVMObjectAllocEventCollector oam;
3970   arrayOop dim_array = check_array(env, dim, true, CHECK_NULL);
3971   oop element_mirror = JNIHandles::resolve(eltClass);
3972   assert(dim_array->is_typeArray(), "just checking");
3973   oop result = Reflection::reflect_new_multi_array(element_mirror, typeArrayOop(dim_array), CHECK_NULL);
3974   return JNIHandles::make_local(env, result);
3975 JVM_END
3976 
3977 
3978 // Networking library support ////////////////////////////////////////////////////////////////////
3979 
3980 JVM_LEAF(jint, JVM_InitializeSocketLibrary())
3981   JVMWrapper("JVM_InitializeSocketLibrary");
3982   return 0;
3983 JVM_END
3984 
3985 
3986 JVM_LEAF(jint, JVM_Socket(jint domain, jint type, jint protocol))
3987   JVMWrapper("JVM_Socket");
3988   return os::socket(domain, type, protocol);
3989 JVM_END
3990 
3991 
3992 JVM_LEAF(jint, JVM_SocketClose(jint fd))
3993   JVMWrapper2("JVM_SocketClose (0x%x)", fd);
3994   //%note jvm_r6
3995   return os::socket_close(fd);
3996 JVM_END
3997 
3998 
3999 JVM_LEAF(jint, JVM_SocketShutdown(jint fd, jint howto))
4000   JVMWrapper2("JVM_SocketShutdown (0x%x)", fd);
4001   //%note jvm_r6
4002   return os::socket_shutdown(fd, howto);
4003 JVM_END
4004 
4005 
4006 JVM_LEAF(jint, JVM_Recv(jint fd, char *buf, jint nBytes, jint flags))
4007   JVMWrapper2("JVM_Recv (0x%x)", fd);
4008   //%note jvm_r6
4009   return os::recv(fd, buf, (size_t)nBytes, (uint)flags);
4010 JVM_END
4011 
4012 
4013 JVM_LEAF(jint, JVM_Send(jint fd, char *buf, jint nBytes, jint flags))
4014   JVMWrapper2("JVM_Send (0x%x)", fd);
4015   //%note jvm_r6
4016   return os::send(fd, buf, (size_t)nBytes, (uint)flags);
4017 JVM_END
4018 
4019 
4020 JVM_LEAF(jint, JVM_Timeout(int fd, long timeout))
4021   JVMWrapper2("JVM_Timeout (0x%x)", fd);
4022   //%note jvm_r6
4023   return os::timeout(fd, timeout);
4024 JVM_END
4025 
4026 
4027 JVM_LEAF(jint, JVM_Listen(jint fd, jint count))
4028   JVMWrapper2("JVM_Listen (0x%x)", fd);
4029   //%note jvm_r6
4030   return os::listen(fd, count);
4031 JVM_END
4032 
4033 
4034 JVM_LEAF(jint, JVM_Connect(jint fd, struct sockaddr *him, jint len))
4035   JVMWrapper2("JVM_Connect (0x%x)", fd);
4036   //%note jvm_r6
4037   return os::connect(fd, him, (socklen_t)len);
4038 JVM_END
4039 
4040 
4041 JVM_LEAF(jint, JVM_Bind(jint fd, struct sockaddr *him, jint len))
4042   JVMWrapper2("JVM_Bind (0x%x)", fd);
4043   //%note jvm_r6
4044   return os::bind(fd, him, (socklen_t)len);
4045 JVM_END
4046 
4047 
4048 JVM_LEAF(jint, JVM_Accept(jint fd, struct sockaddr *him, jint *len))
4049   JVMWrapper2("JVM_Accept (0x%x)", fd);
4050   //%note jvm_r6
4051   socklen_t socklen = (socklen_t)(*len);
4052   jint result = os::accept(fd, him, &socklen);
4053   *len = (jint)socklen;
4054   return result;
4055 JVM_END
4056 
4057 
4058 JVM_LEAF(jint, JVM_RecvFrom(jint fd, char *buf, int nBytes, int flags, struct sockaddr *from, int *fromlen))
4059   JVMWrapper2("JVM_RecvFrom (0x%x)", fd);
4060   //%note jvm_r6
4061   socklen_t socklen = (socklen_t)(*fromlen);
4062   jint result = os::recvfrom(fd, buf, (size_t)nBytes, (uint)flags, from, &socklen);
4063   *fromlen = (int)socklen;
4064   return result;
4065 JVM_END
4066 
4067 
4068 JVM_LEAF(jint, JVM_GetSockName(jint fd, struct sockaddr *him, int *len))
4069   JVMWrapper2("JVM_GetSockName (0x%x)", fd);
4070   //%note jvm_r6
4071   socklen_t socklen = (socklen_t)(*len);
4072   jint result = os::get_sock_name(fd, him, &socklen);
4073   *len = (int)socklen;
4074   return result;
4075 JVM_END
4076 
4077 
4078 JVM_LEAF(jint, JVM_SendTo(jint fd, char *buf, int len, int flags, struct sockaddr *to, int tolen))
4079   JVMWrapper2("JVM_SendTo (0x%x)", fd);
4080   //%note jvm_r6
4081   return os::sendto(fd, buf, (size_t)len, (uint)flags, to, (socklen_t)tolen);
4082 JVM_END
4083 
4084 
4085 JVM_LEAF(jint, JVM_SocketAvailable(jint fd, jint *pbytes))
4086   JVMWrapper2("JVM_SocketAvailable (0x%x)", fd);
4087   //%note jvm_r6
4088   return os::socket_available(fd, pbytes);
4089 JVM_END
4090 
4091 
4092 JVM_LEAF(jint, JVM_GetSockOpt(jint fd, int level, int optname, char *optval, int *optlen))
4093   JVMWrapper2("JVM_GetSockOpt (0x%x)", fd);
4094   //%note jvm_r6
4095   socklen_t socklen = (socklen_t)(*optlen);
4096   jint result = os::get_sock_opt(fd, level, optname, optval, &socklen);
4097   *optlen = (int)socklen;
4098   return result;
4099 JVM_END
4100 
4101 
4102 JVM_LEAF(jint, JVM_SetSockOpt(jint fd, int level, int optname, const char *optval, int optlen))
4103   JVMWrapper2("JVM_GetSockOpt (0x%x)", fd);
4104   //%note jvm_r6
4105   return os::set_sock_opt(fd, level, optname, optval, (socklen_t)optlen);
4106 JVM_END
4107 
4108 
4109 JVM_LEAF(int, JVM_GetHostName(char* name, int namelen))
4110   JVMWrapper("JVM_GetHostName");
4111   return os::get_host_name(name, namelen);
4112 JVM_END
4113 
4114 
4115 // Library support ///////////////////////////////////////////////////////////////////////////
4116 
4117 JVM_ENTRY_NO_ENV(void*, JVM_LoadLibrary(const char* name))
4118   //%note jvm_ct
4119   JVMWrapper2("JVM_LoadLibrary (%s)", name);
4120   char ebuf[1024];
4121   void *load_result;
4122   {
4123     ThreadToNativeFromVM ttnfvm(thread);
4124     load_result = os::dll_load(name, ebuf, sizeof ebuf);
4125   }
4126   if (load_result == NULL) {
4127     char msg[1024];
4128     jio_snprintf(msg, sizeof msg, "%s: %s", name, ebuf);
4129     // Since 'ebuf' may contain a string encoded using
4130     // platform encoding scheme, we need to pass
4131     // Exceptions::unsafe_to_utf8 to the new_exception method
4132     // as the last argument. See bug 6367357.
4133     Handle h_exception =
4134       Exceptions::new_exception(thread,
4135                                 vmSymbols::java_lang_UnsatisfiedLinkError(),
4136                                 msg, Exceptions::unsafe_to_utf8);
4137 
4138     THROW_HANDLE_0(h_exception);
4139   }
4140   return load_result;
4141 JVM_END
4142 
4143 
4144 JVM_LEAF(void, JVM_UnloadLibrary(void* handle))
4145   JVMWrapper("JVM_UnloadLibrary");
4146   os::dll_unload(handle);
4147 JVM_END
4148 
4149 
4150 JVM_LEAF(void*, JVM_FindLibraryEntry(void* handle, const char* name))
4151   JVMWrapper2("JVM_FindLibraryEntry (%s)", name);
4152   return os::dll_lookup(handle, name);
4153 JVM_END
4154 
4155 
4156 // Floating point support ////////////////////////////////////////////////////////////////////
4157 
4158 JVM_LEAF(jboolean, JVM_IsNaN(jdouble a))
4159   JVMWrapper("JVM_IsNaN");
4160   return g_isnan(a);
4161 JVM_END
4162 
4163 
4164 // JNI version ///////////////////////////////////////////////////////////////////////////////
4165 
4166 JVM_LEAF(jboolean, JVM_IsSupportedJNIVersion(jint version))
4167   JVMWrapper2("JVM_IsSupportedJNIVersion (%d)", version);
4168   return Threads::is_supported_jni_version_including_1_1(version);
4169 JVM_END
4170 
4171 
4172 // String support ///////////////////////////////////////////////////////////////////////////
4173 
4174 JVM_ENTRY(jstring, JVM_InternString(JNIEnv *env, jstring str))
4175   JVMWrapper("JVM_InternString");
4176   JvmtiVMObjectAllocEventCollector oam;
4177   if (str == NULL) return NULL;
4178   oop string = JNIHandles::resolve_non_null(str);
4179   oop result = StringTable::intern(string, CHECK_NULL);
4180   return (jstring) JNIHandles::make_local(env, result);
4181 JVM_END
4182 
4183 
4184 // Raw monitor support //////////////////////////////////////////////////////////////////////
4185 
4186 // The lock routine below calls lock_without_safepoint_check in order to get a raw lock
4187 // without interfering with the safepoint mechanism. The routines are not JVM_LEAF because
4188 // they might be called by non-java threads. The JVM_LEAF installs a NoHandleMark check
4189 // that only works with java threads.
4190 
4191 
4192 JNIEXPORT void* JNICALL JVM_RawMonitorCreate(void) {
4193   VM_Exit::block_if_vm_exited();
4194   JVMWrapper("JVM_RawMonitorCreate");
4195   return new Mutex(Mutex::native, "JVM_RawMonitorCreate");
4196 }
4197 
4198 
4199 JNIEXPORT void JNICALL  JVM_RawMonitorDestroy(void *mon) {
4200   VM_Exit::block_if_vm_exited();
4201   JVMWrapper("JVM_RawMonitorDestroy");
4202   delete ((Mutex*) mon);
4203 }
4204 
4205 
4206 JNIEXPORT jint JNICALL JVM_RawMonitorEnter(void *mon) {
4207   VM_Exit::block_if_vm_exited();
4208   JVMWrapper("JVM_RawMonitorEnter");
4209   ((Mutex*) mon)->jvm_raw_lock();
4210   return 0;
4211 }
4212 
4213 
4214 JNIEXPORT void JNICALL JVM_RawMonitorExit(void *mon) {
4215   VM_Exit::block_if_vm_exited();
4216   JVMWrapper("JVM_RawMonitorExit");
4217   ((Mutex*) mon)->jvm_raw_unlock();
4218 }
4219 
4220 
4221 // Support for Serialization
4222 
4223 typedef jfloat  (JNICALL *IntBitsToFloatFn  )(JNIEnv* env, jclass cb, jint    value);
4224 typedef jdouble (JNICALL *LongBitsToDoubleFn)(JNIEnv* env, jclass cb, jlong   value);
4225 typedef jint    (JNICALL *FloatToIntBitsFn  )(JNIEnv* env, jclass cb, jfloat  value);
4226 typedef jlong   (JNICALL *DoubleToLongBitsFn)(JNIEnv* env, jclass cb, jdouble value);
4227 
4228 static IntBitsToFloatFn   int_bits_to_float_fn   = NULL;
4229 static LongBitsToDoubleFn long_bits_to_double_fn = NULL;
4230 static FloatToIntBitsFn   float_to_int_bits_fn   = NULL;
4231 static DoubleToLongBitsFn double_to_long_bits_fn = NULL;
4232 
4233 
4234 void initialize_converter_functions() {
4235   if (JDK_Version::is_gte_jdk14x_version()) {
4236     // These functions only exist for compatibility with 1.3.1 and earlier
4237     return;
4238   }
4239 
4240   // called from universe_post_init()
4241   assert(
4242     int_bits_to_float_fn   == NULL &&
4243     long_bits_to_double_fn == NULL &&
4244     float_to_int_bits_fn   == NULL &&
4245     double_to_long_bits_fn == NULL ,
4246     "initialization done twice"
4247   );
4248   // initialize
4249   int_bits_to_float_fn   = CAST_TO_FN_PTR(IntBitsToFloatFn  , NativeLookup::base_library_lookup("java/lang/Float" , "intBitsToFloat"  , "(I)F"));
4250   long_bits_to_double_fn = CAST_TO_FN_PTR(LongBitsToDoubleFn, NativeLookup::base_library_lookup("java/lang/Double", "longBitsToDouble", "(J)D"));
4251   float_to_int_bits_fn   = CAST_TO_FN_PTR(FloatToIntBitsFn  , NativeLookup::base_library_lookup("java/lang/Float" , "floatToIntBits"  , "(F)I"));
4252   double_to_long_bits_fn = CAST_TO_FN_PTR(DoubleToLongBitsFn, NativeLookup::base_library_lookup("java/lang/Double", "doubleToLongBits", "(D)J"));
4253   // verify
4254   assert(
4255     int_bits_to_float_fn   != NULL &&
4256     long_bits_to_double_fn != NULL &&
4257     float_to_int_bits_fn   != NULL &&
4258     double_to_long_bits_fn != NULL ,
4259     "initialization failed"
4260   );
4261 }
4262 
4263 
4264 
4265 // Shared JNI/JVM entry points //////////////////////////////////////////////////////////////
4266 
4267 jclass find_class_from_class_loader(JNIEnv* env, Symbol* name, jboolean init,
4268                                     Handle loader, Handle protection_domain,
4269                                     jboolean throwError, TRAPS) {
4270   // Security Note:
4271   //   The Java level wrapper will perform the necessary security check allowing
4272   //   us to pass the NULL as the initiating class loader.  The VM is responsible for
4273   //   the checkPackageAccess relative to the initiating class loader via the
4274   //   protection_domain. The protection_domain is passed as NULL by the java code
4275   //   if there is no security manager in 3-arg Class.forName().
4276   Klass* klass = SystemDictionary::resolve_or_fail(name, loader, protection_domain, throwError != 0, CHECK_NULL);
4277 
4278   KlassHandle klass_handle(THREAD, klass);
4279   // Check if we should initialize the class
4280   if (init && klass_handle->oop_is_instance()) {
4281     klass_handle->initialize(CHECK_NULL);
4282   }
4283   return (jclass) JNIHandles::make_local(env, klass_handle->java_mirror());
4284 }
4285 
4286 
4287 // Internal SQE debugging support ///////////////////////////////////////////////////////////
4288 
4289 #ifndef PRODUCT
4290 
4291 extern "C" {
4292   JNIEXPORT jboolean JNICALL JVM_AccessVMBooleanFlag(const char* name, jboolean* value, jboolean is_get);
4293   JNIEXPORT jboolean JNICALL JVM_AccessVMIntFlag(const char* name, jint* value, jboolean is_get);
4294   JNIEXPORT void JNICALL JVM_VMBreakPoint(JNIEnv *env, jobject obj);
4295 }
4296 
4297 JVM_LEAF(jboolean, JVM_AccessVMBooleanFlag(const char* name, jboolean* value, jboolean is_get))
4298   JVMWrapper("JVM_AccessBoolVMFlag");
4299   return is_get ? CommandLineFlags::boolAt((char*) name, (bool*) value) : CommandLineFlags::boolAtPut((char*) name, (bool*) value, Flag::INTERNAL);
4300 JVM_END
4301 
4302 JVM_LEAF(jboolean, JVM_AccessVMIntFlag(const char* name, jint* value, jboolean is_get))
4303   JVMWrapper("JVM_AccessVMIntFlag");
4304   intx v;
4305   jboolean result = is_get ? CommandLineFlags::intxAt((char*) name, &v) : CommandLineFlags::intxAtPut((char*) name, &v, Flag::INTERNAL);
4306   *value = (jint)v;
4307   return result;
4308 JVM_END
4309 
4310 
4311 JVM_ENTRY(void, JVM_VMBreakPoint(JNIEnv *env, jobject obj))
4312   JVMWrapper("JVM_VMBreakPoint");
4313   oop the_obj = JNIHandles::resolve(obj);
4314   BREAKPOINT;
4315 JVM_END
4316 
4317 
4318 #endif
4319 
4320 
4321 // Method ///////////////////////////////////////////////////////////////////////////////////////////
4322 
4323 JVM_ENTRY(jobject, JVM_InvokeMethod(JNIEnv *env, jobject method, jobject obj, jobjectArray args0))
4324   JVMWrapper("JVM_InvokeMethod");
4325   Handle method_handle;
4326   if (thread->stack_available((address) &method_handle) >= JVMInvokeMethodSlack) {
4327     method_handle = Handle(THREAD, JNIHandles::resolve(method));
4328     Handle receiver(THREAD, JNIHandles::resolve(obj));
4329     objArrayHandle args(THREAD, objArrayOop(JNIHandles::resolve(args0)));
4330     oop result = Reflection::invoke_method(method_handle(), receiver, args, CHECK_NULL);
4331     jobject res = JNIHandles::make_local(env, result);
4332     if (JvmtiExport::should_post_vm_object_alloc()) {
4333       oop ret_type = java_lang_reflect_Method::return_type(method_handle());
4334       assert(ret_type != NULL, "sanity check: ret_type oop must not be NULL!");
4335       if (java_lang_Class::is_primitive(ret_type)) {
4336         // Only for primitive type vm allocates memory for java object.
4337         // See box() method.
4338         JvmtiExport::post_vm_object_alloc(JavaThread::current(), result);
4339       }
4340     }
4341     return res;
4342   } else {
4343     THROW_0(vmSymbols::java_lang_StackOverflowError());
4344   }
4345 JVM_END
4346 
4347 
4348 JVM_ENTRY(jobject, JVM_NewInstanceFromConstructor(JNIEnv *env, jobject c, jobjectArray args0))
4349   JVMWrapper("JVM_NewInstanceFromConstructor");
4350   oop constructor_mirror = JNIHandles::resolve(c);
4351   objArrayHandle args(THREAD, objArrayOop(JNIHandles::resolve(args0)));
4352   oop result = Reflection::invoke_constructor(constructor_mirror, args, CHECK_NULL);
4353   jobject res = JNIHandles::make_local(env, result);
4354   if (JvmtiExport::should_post_vm_object_alloc()) {
4355     JvmtiExport::post_vm_object_alloc(JavaThread::current(), result);
4356   }
4357   return res;
4358 JVM_END
4359 
4360 // Atomic ///////////////////////////////////////////////////////////////////////////////////////////
4361 
4362 JVM_LEAF(jboolean, JVM_SupportsCX8())
4363   JVMWrapper("JVM_SupportsCX8");
4364   return VM_Version::supports_cx8();
4365 JVM_END
4366 
4367 
4368 JVM_ENTRY(jboolean, JVM_CX8Field(JNIEnv *env, jobject obj, jfieldID fid, jlong oldVal, jlong newVal))
4369   JVMWrapper("JVM_CX8Field");
4370   jlong res;
4371   oop             o       = JNIHandles::resolve(obj);
4372   intptr_t        fldOffs = jfieldIDWorkaround::from_instance_jfieldID(o->klass(), fid);
4373   volatile jlong* addr    = (volatile jlong*)((address)o + fldOffs);
4374 
4375   assert(VM_Version::supports_cx8(), "cx8 not supported");
4376   res = Atomic::cmpxchg(newVal, addr, oldVal);
4377 
4378   return res == oldVal;
4379 JVM_END
4380 
4381 // DTrace ///////////////////////////////////////////////////////////////////
4382 
4383 JVM_ENTRY(jint, JVM_DTraceGetVersion(JNIEnv* env))
4384   JVMWrapper("JVM_DTraceGetVersion");
4385   return (jint)JVM_TRACING_DTRACE_VERSION;
4386 JVM_END
4387 
4388 JVM_ENTRY(jlong,JVM_DTraceActivate(
4389     JNIEnv* env, jint version, jstring module_name, jint providers_count,
4390     JVM_DTraceProvider* providers))
4391   JVMWrapper("JVM_DTraceActivate");
4392   return DTraceJSDT::activate(
4393     version, module_name, providers_count, providers, THREAD);
4394 JVM_END
4395 
4396 JVM_ENTRY(jboolean,JVM_DTraceIsProbeEnabled(JNIEnv* env, jmethodID method))
4397   JVMWrapper("JVM_DTraceIsProbeEnabled");
4398   return DTraceJSDT::is_probe_enabled(method);
4399 JVM_END
4400 
4401 JVM_ENTRY(void,JVM_DTraceDispose(JNIEnv* env, jlong handle))
4402   JVMWrapper("JVM_DTraceDispose");
4403   DTraceJSDT::dispose(handle);
4404 JVM_END
4405 
4406 JVM_ENTRY(jboolean,JVM_DTraceIsSupported(JNIEnv* env))
4407   JVMWrapper("JVM_DTraceIsSupported");
4408   return DTraceJSDT::is_supported();
4409 JVM_END
4410 
4411 // Returns an array of all live Thread objects (VM internal JavaThreads,
4412 // jvmti agent threads, and JNI attaching threads  are skipped)
4413 // See CR 6404306 regarding JNI attaching threads
4414 JVM_ENTRY(jobjectArray, JVM_GetAllThreads(JNIEnv *env, jclass dummy))
4415   ResourceMark rm(THREAD);
4416   ThreadsListEnumerator tle(THREAD, false, false);
4417   JvmtiVMObjectAllocEventCollector oam;
4418 
4419   int num_threads = tle.num_threads();
4420   objArrayOop r = oopFactory::new_objArray(SystemDictionary::Thread_klass(), num_threads, CHECK_NULL);
4421   objArrayHandle threads_ah(THREAD, r);
4422 
4423   for (int i = 0; i < num_threads; i++) {
4424     Handle h = tle.get_threadObj(i);
4425     threads_ah->obj_at_put(i, h());
4426   }
4427 
4428   return (jobjectArray) JNIHandles::make_local(env, threads_ah());
4429 JVM_END
4430 
4431 
4432 // Support for java.lang.Thread.getStackTrace() and getAllStackTraces() methods
4433 // Return StackTraceElement[][], each element is the stack trace of a thread in
4434 // the corresponding entry in the given threads array
4435 JVM_ENTRY(jobjectArray, JVM_DumpThreads(JNIEnv *env, jclass threadClass, jobjectArray threads))
4436   JVMWrapper("JVM_DumpThreads");
4437   JvmtiVMObjectAllocEventCollector oam;
4438 
4439   // Check if threads is null
4440   if (threads == NULL) {
4441     THROW_(vmSymbols::java_lang_NullPointerException(), 0);
4442   }
4443 
4444   objArrayOop a = objArrayOop(JNIHandles::resolve_non_null(threads));
4445   objArrayHandle ah(THREAD, a);
4446   int num_threads = ah->length();
4447   // check if threads is non-empty array
4448   if (num_threads == 0) {
4449     THROW_(vmSymbols::java_lang_IllegalArgumentException(), 0);
4450   }
4451 
4452   // check if threads is not an array of objects of Thread class
4453   Klass* k = ObjArrayKlass::cast(ah->klass())->element_klass();
4454   if (k != SystemDictionary::Thread_klass()) {
4455     THROW_(vmSymbols::java_lang_IllegalArgumentException(), 0);
4456   }
4457 
4458   ResourceMark rm(THREAD);
4459 
4460   GrowableArray<instanceHandle>* thread_handle_array = new GrowableArray<instanceHandle>(num_threads);
4461   for (int i = 0; i < num_threads; i++) {
4462     oop thread_obj = ah->obj_at(i);
4463     instanceHandle h(THREAD, (instanceOop) thread_obj);
4464     thread_handle_array->append(h);
4465   }
4466 
4467   Handle stacktraces = ThreadService::dump_stack_traces(thread_handle_array, num_threads, CHECK_NULL);
4468   return (jobjectArray)JNIHandles::make_local(env, stacktraces());
4469 
4470 JVM_END
4471 
4472 // JVM monitoring and management support
4473 JVM_ENTRY_NO_ENV(void*, JVM_GetManagement(jint version))
4474   return Management::get_jmm_interface(version);
4475 JVM_END
4476 
4477 // com.sun.tools.attach.VirtualMachine agent properties support
4478 //
4479 // Initialize the agent properties with the properties maintained in the VM
4480 JVM_ENTRY(jobject, JVM_InitAgentProperties(JNIEnv *env, jobject properties))
4481   JVMWrapper("JVM_InitAgentProperties");
4482   ResourceMark rm;
4483 
4484   Handle props(THREAD, JNIHandles::resolve_non_null(properties));
4485 
4486   PUTPROP(props, "sun.java.command", Arguments::java_command());
4487   PUTPROP(props, "sun.jvm.flags", Arguments::jvm_flags());
4488   PUTPROP(props, "sun.jvm.args", Arguments::jvm_args());
4489   return properties;
4490 JVM_END
4491 
4492 JVM_ENTRY(jobjectArray, JVM_GetEnclosingMethodInfo(JNIEnv *env, jclass ofClass))
4493 {
4494   JVMWrapper("JVM_GetEnclosingMethodInfo");
4495   JvmtiVMObjectAllocEventCollector oam;
4496 
4497   if (ofClass == NULL) {
4498     return NULL;
4499   }
4500   Handle mirror(THREAD, JNIHandles::resolve_non_null(ofClass));
4501   // Special handling for primitive objects
4502   if (java_lang_Class::is_primitive(mirror())) {
4503     return NULL;
4504   }
4505   Klass* k = java_lang_Class::as_Klass(mirror());
4506   if (!k->oop_is_instance()) {
4507     return NULL;
4508   }
4509   instanceKlassHandle ik_h(THREAD, k);
4510   int encl_method_class_idx = ik_h->enclosing_method_class_index();
4511   if (encl_method_class_idx == 0) {
4512     return NULL;
4513   }
4514   objArrayOop dest_o = oopFactory::new_objArray(SystemDictionary::Object_klass(), 3, CHECK_NULL);
4515   objArrayHandle dest(THREAD, dest_o);
4516   Klass* enc_k = ik_h->constants()->klass_at(encl_method_class_idx, CHECK_NULL);
4517   dest->obj_at_put(0, enc_k->java_mirror());
4518   int encl_method_method_idx = ik_h->enclosing_method_method_index();
4519   if (encl_method_method_idx != 0) {
4520     Symbol* sym = ik_h->constants()->symbol_at(
4521                         extract_low_short_from_int(
4522                           ik_h->constants()->name_and_type_at(encl_method_method_idx)));
4523     Handle str = java_lang_String::create_from_symbol(sym, CHECK_NULL);
4524     dest->obj_at_put(1, str());
4525     sym = ik_h->constants()->symbol_at(
4526               extract_high_short_from_int(
4527                 ik_h->constants()->name_and_type_at(encl_method_method_idx)));
4528     str = java_lang_String::create_from_symbol(sym, CHECK_NULL);
4529     dest->obj_at_put(2, str());
4530   }
4531   return (jobjectArray) JNIHandles::make_local(dest());
4532 }
4533 JVM_END
4534 
4535 JVM_ENTRY(jintArray, JVM_GetThreadStateValues(JNIEnv* env,
4536                                               jint javaThreadState))
4537 {
4538   // If new thread states are added in future JDK and VM versions,
4539   // this should check if the JDK version is compatible with thread
4540   // states supported by the VM.  Return NULL if not compatible.
4541   //
4542   // This function must map the VM java_lang_Thread::ThreadStatus
4543   // to the Java thread state that the JDK supports.
4544   //
4545 
4546   typeArrayHandle values_h;
4547   switch (javaThreadState) {
4548     case JAVA_THREAD_STATE_NEW : {
4549       typeArrayOop r = oopFactory::new_typeArray(T_INT, 1, CHECK_NULL);
4550       values_h = typeArrayHandle(THREAD, r);
4551       values_h->int_at_put(0, java_lang_Thread::NEW);
4552       break;
4553     }
4554     case JAVA_THREAD_STATE_RUNNABLE : {
4555       typeArrayOop r = oopFactory::new_typeArray(T_INT, 1, CHECK_NULL);
4556       values_h = typeArrayHandle(THREAD, r);
4557       values_h->int_at_put(0, java_lang_Thread::RUNNABLE);
4558       break;
4559     }
4560     case JAVA_THREAD_STATE_BLOCKED : {
4561       typeArrayOop r = oopFactory::new_typeArray(T_INT, 1, CHECK_NULL);
4562       values_h = typeArrayHandle(THREAD, r);
4563       values_h->int_at_put(0, java_lang_Thread::BLOCKED_ON_MONITOR_ENTER);
4564       break;
4565     }
4566     case JAVA_THREAD_STATE_WAITING : {
4567       typeArrayOop r = oopFactory::new_typeArray(T_INT, 2, CHECK_NULL);
4568       values_h = typeArrayHandle(THREAD, r);
4569       values_h->int_at_put(0, java_lang_Thread::IN_OBJECT_WAIT);
4570       values_h->int_at_put(1, java_lang_Thread::PARKED);
4571       break;
4572     }
4573     case JAVA_THREAD_STATE_TIMED_WAITING : {
4574       typeArrayOop r = oopFactory::new_typeArray(T_INT, 3, CHECK_NULL);
4575       values_h = typeArrayHandle(THREAD, r);
4576       values_h->int_at_put(0, java_lang_Thread::SLEEPING);
4577       values_h->int_at_put(1, java_lang_Thread::IN_OBJECT_WAIT_TIMED);
4578       values_h->int_at_put(2, java_lang_Thread::PARKED_TIMED);
4579       break;
4580     }
4581     case JAVA_THREAD_STATE_TERMINATED : {
4582       typeArrayOop r = oopFactory::new_typeArray(T_INT, 1, CHECK_NULL);
4583       values_h = typeArrayHandle(THREAD, r);
4584       values_h->int_at_put(0, java_lang_Thread::TERMINATED);
4585       break;
4586     }
4587     default:
4588       // Unknown state - probably incompatible JDK version
4589       return NULL;
4590   }
4591 
4592   return (jintArray) JNIHandles::make_local(env, values_h());
4593 }
4594 JVM_END
4595 
4596 
4597 JVM_ENTRY(jobjectArray, JVM_GetThreadStateNames(JNIEnv* env,
4598                                                 jint javaThreadState,
4599                                                 jintArray values))
4600 {
4601   // If new thread states are added in future JDK and VM versions,
4602   // this should check if the JDK version is compatible with thread
4603   // states supported by the VM.  Return NULL if not compatible.
4604   //
4605   // This function must map the VM java_lang_Thread::ThreadStatus
4606   // to the Java thread state that the JDK supports.
4607   //
4608 
4609   ResourceMark rm;
4610 
4611   // Check if threads is null
4612   if (values == NULL) {
4613     THROW_(vmSymbols::java_lang_NullPointerException(), 0);
4614   }
4615 
4616   typeArrayOop v = typeArrayOop(JNIHandles::resolve_non_null(values));
4617   typeArrayHandle values_h(THREAD, v);
4618 
4619   objArrayHandle names_h;
4620   switch (javaThreadState) {
4621     case JAVA_THREAD_STATE_NEW : {
4622       assert(values_h->length() == 1 &&
4623                values_h->int_at(0) == java_lang_Thread::NEW,
4624              "Invalid threadStatus value");
4625 
4626       objArrayOop r = oopFactory::new_objArray(SystemDictionary::String_klass(),
4627                                                1, /* only 1 substate */
4628                                                CHECK_NULL);
4629       names_h = objArrayHandle(THREAD, r);
4630       Handle name = java_lang_String::create_from_str("NEW", CHECK_NULL);
4631       names_h->obj_at_put(0, name());
4632       break;
4633     }
4634     case JAVA_THREAD_STATE_RUNNABLE : {
4635       assert(values_h->length() == 1 &&
4636                values_h->int_at(0) == java_lang_Thread::RUNNABLE,
4637              "Invalid threadStatus value");
4638 
4639       objArrayOop r = oopFactory::new_objArray(SystemDictionary::String_klass(),
4640                                                1, /* only 1 substate */
4641                                                CHECK_NULL);
4642       names_h = objArrayHandle(THREAD, r);
4643       Handle name = java_lang_String::create_from_str("RUNNABLE", CHECK_NULL);
4644       names_h->obj_at_put(0, name());
4645       break;
4646     }
4647     case JAVA_THREAD_STATE_BLOCKED : {
4648       assert(values_h->length() == 1 &&
4649                values_h->int_at(0) == java_lang_Thread::BLOCKED_ON_MONITOR_ENTER,
4650              "Invalid threadStatus value");
4651 
4652       objArrayOop r = oopFactory::new_objArray(SystemDictionary::String_klass(),
4653                                                1, /* only 1 substate */
4654                                                CHECK_NULL);
4655       names_h = objArrayHandle(THREAD, r);
4656       Handle name = java_lang_String::create_from_str("BLOCKED", CHECK_NULL);
4657       names_h->obj_at_put(0, name());
4658       break;
4659     }
4660     case JAVA_THREAD_STATE_WAITING : {
4661       assert(values_h->length() == 2 &&
4662                values_h->int_at(0) == java_lang_Thread::IN_OBJECT_WAIT &&
4663                values_h->int_at(1) == java_lang_Thread::PARKED,
4664              "Invalid threadStatus value");
4665       objArrayOop r = oopFactory::new_objArray(SystemDictionary::String_klass(),
4666                                                2, /* number of substates */
4667                                                CHECK_NULL);
4668       names_h = objArrayHandle(THREAD, r);
4669       Handle name0 = java_lang_String::create_from_str("WAITING.OBJECT_WAIT",
4670                                                        CHECK_NULL);
4671       Handle name1 = java_lang_String::create_from_str("WAITING.PARKED",
4672                                                        CHECK_NULL);
4673       names_h->obj_at_put(0, name0());
4674       names_h->obj_at_put(1, name1());
4675       break;
4676     }
4677     case JAVA_THREAD_STATE_TIMED_WAITING : {
4678       assert(values_h->length() == 3 &&
4679                values_h->int_at(0) == java_lang_Thread::SLEEPING &&
4680                values_h->int_at(1) == java_lang_Thread::IN_OBJECT_WAIT_TIMED &&
4681                values_h->int_at(2) == java_lang_Thread::PARKED_TIMED,
4682              "Invalid threadStatus value");
4683       objArrayOop r = oopFactory::new_objArray(SystemDictionary::String_klass(),
4684                                                3, /* number of substates */
4685                                                CHECK_NULL);
4686       names_h = objArrayHandle(THREAD, r);
4687       Handle name0 = java_lang_String::create_from_str("TIMED_WAITING.SLEEPING",
4688                                                        CHECK_NULL);
4689       Handle name1 = java_lang_String::create_from_str("TIMED_WAITING.OBJECT_WAIT",
4690                                                        CHECK_NULL);
4691       Handle name2 = java_lang_String::create_from_str("TIMED_WAITING.PARKED",
4692                                                        CHECK_NULL);
4693       names_h->obj_at_put(0, name0());
4694       names_h->obj_at_put(1, name1());
4695       names_h->obj_at_put(2, name2());
4696       break;
4697     }
4698     case JAVA_THREAD_STATE_TERMINATED : {
4699       assert(values_h->length() == 1 &&
4700                values_h->int_at(0) == java_lang_Thread::TERMINATED,
4701              "Invalid threadStatus value");
4702       objArrayOop r = oopFactory::new_objArray(SystemDictionary::String_klass(),
4703                                                1, /* only 1 substate */
4704                                                CHECK_NULL);
4705       names_h = objArrayHandle(THREAD, r);
4706       Handle name = java_lang_String::create_from_str("TERMINATED", CHECK_NULL);
4707       names_h->obj_at_put(0, name());
4708       break;
4709     }
4710     default:
4711       // Unknown state - probably incompatible JDK version
4712       return NULL;
4713   }
4714   return (jobjectArray) JNIHandles::make_local(env, names_h());
4715 }
4716 JVM_END
4717 
4718 JVM_ENTRY(void, JVM_GetVersionInfo(JNIEnv* env, jvm_version_info* info, size_t info_size))
4719 {
4720   memset(info, 0, info_size);
4721 
4722   info->jvm_version = Abstract_VM_Version::jvm_version();
4723   info->update_version = 0;          /* 0 in HotSpot Express VM */
4724   info->special_update_version = 0;  /* 0 in HotSpot Express VM */
4725 
4726   // when we add a new capability in the jvm_version_info struct, we should also
4727   // consider to expose this new capability in the sun.rt.jvmCapabilities jvmstat
4728   // counter defined in runtimeService.cpp.
4729   info->is_attachable = AttachListener::is_attach_supported();
4730 }
4731 JVM_END