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