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