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