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