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