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