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