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