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 (0 != num_params) {
1802     // make sure all the symbols are properly formatted
1803     for (int i = 0; i < num_params; i++) {
1804       MethodParametersElement* params = mh->method_parameters_start();
1805       int index = params[i].name_cp_index;
1806       bounds_check(mh->constants(), index, CHECK_NULL);
1807 
1808       if (0 != index && !mh->constants()->tag_at(index).is_utf8()) {
1809         THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
1810                     "Wrong type at constant pool index");
1811       }
1812 
1813     }
1814 
1815     objArrayOop result_oop = oopFactory::new_objArray(SystemDictionary::reflect_Parameter_klass(), num_params, CHECK_NULL);
1816     objArrayHandle result (THREAD, result_oop);
1817 
1818     for (int i = 0; i < num_params; i++) {
1819       MethodParametersElement* params = mh->method_parameters_start();
1820       // For a 0 index, give a NULL symbol
1821       Symbol* sym = 0 != params[i].name_cp_index ?
1822         mh->constants()->symbol_at(params[i].name_cp_index) : NULL;
1823       int flags = params[i].flags;
1824       oop param = Reflection::new_parameter(reflected_method, i, sym,
1825                                             flags, CHECK_NULL);
1826       result->obj_at_put(i, param);
1827     }
1828     return (jobjectArray)JNIHandles::make_local(env, result());
1829   } else {
1830     return (jobjectArray)NULL;
1831   }
1832 }
1833 JVM_END
1834 
1835 // New (JDK 1.4) reflection implementation /////////////////////////////////////
1836 
1837 JVM_ENTRY(jobjectArray, JVM_GetClassDeclaredFields(JNIEnv *env, jclass ofClass, jboolean publicOnly))
1838 {
1839   JVMWrapper("JVM_GetClassDeclaredFields");
1840   JvmtiVMObjectAllocEventCollector oam;
1841 
1842   // Exclude primitive types and array types
1843   if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(ofClass)) ||
1844       java_lang_Class::as_Klass(JNIHandles::resolve_non_null(ofClass))->oop_is_array()) {
1845     // Return empty array
1846     oop res = oopFactory::new_objArray(SystemDictionary::reflect_Field_klass(), 0, CHECK_NULL);
1847     return (jobjectArray) JNIHandles::make_local(env, res);
1848   }
1849 
1850   instanceKlassHandle k(THREAD, java_lang_Class::as_Klass(JNIHandles::resolve_non_null(ofClass)));
1851   constantPoolHandle cp(THREAD, k->constants());
1852 
1853   // Ensure class is linked
1854   k->link_class(CHECK_NULL);
1855 
1856   // 4496456 We need to filter out java.lang.Throwable.backtrace
1857   bool skip_backtrace = false;
1858 
1859   // Allocate result
1860   int num_fields;
1861 
1862   if (publicOnly) {
1863     num_fields = 0;
1864     for (JavaFieldStream fs(k()); !fs.done(); fs.next()) {
1865       if (fs.access_flags().is_public()) ++num_fields;
1866     }
1867   } else {
1868     num_fields = k->java_fields_count();
1869 
1870     if (k() == SystemDictionary::Throwable_klass()) {
1871       num_fields--;
1872       skip_backtrace = true;
1873     }
1874   }
1875 
1876   objArrayOop r = oopFactory::new_objArray(SystemDictionary::reflect_Field_klass(), num_fields, CHECK_NULL);
1877   objArrayHandle result (THREAD, r);
1878 
1879   int out_idx = 0;
1880   fieldDescriptor fd;
1881   for (JavaFieldStream fs(k); !fs.done(); fs.next()) {
1882     if (skip_backtrace) {
1883       // 4496456 skip java.lang.Throwable.backtrace
1884       int offset = fs.offset();
1885       if (offset == java_lang_Throwable::get_backtrace_offset()) continue;
1886     }
1887 
1888     if (!publicOnly || fs.access_flags().is_public()) {
1889       fd.reinitialize(k(), fs.index());
1890       oop field = Reflection::new_field(&fd, CHECK_NULL);
1891       result->obj_at_put(out_idx, field);
1892       ++out_idx;
1893     }
1894   }
1895   assert(out_idx == num_fields, "just checking");
1896   return (jobjectArray) JNIHandles::make_local(env, result());
1897 }
1898 JVM_END
1899 
1900 static bool select_method(methodHandle method, bool want_constructor) {
1901   if (want_constructor) {
1902     return (method->is_initializer() && !method->is_static());
1903   } else {
1904     return  (!method->is_initializer() && !method->is_overpass());
1905   }
1906 }
1907 
1908 static jobjectArray get_class_declared_methods_helper(
1909                                   JNIEnv *env,
1910                                   jclass ofClass, jboolean publicOnly,
1911                                   bool want_constructor,
1912                                   Klass* klass, TRAPS) {
1913 
1914   JvmtiVMObjectAllocEventCollector oam;
1915 
1916   // Exclude primitive types and array types
1917   if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(ofClass))
1918       || java_lang_Class::as_Klass(JNIHandles::resolve_non_null(ofClass))->oop_is_array()) {
1919     // Return empty array
1920     oop res = oopFactory::new_objArray(klass, 0, CHECK_NULL);
1921     return (jobjectArray) JNIHandles::make_local(env, res);
1922   }
1923 
1924   instanceKlassHandle k(THREAD, java_lang_Class::as_Klass(JNIHandles::resolve_non_null(ofClass)));
1925 
1926   // Ensure class is linked
1927   k->link_class(CHECK_NULL);
1928 
1929   Array<Method*>* methods = k->methods();
1930   int methods_length = methods->length();
1931 
1932   // Save original method_idnum in case of redefinition, which can change
1933   // the idnum of obsolete methods.  The new method will have the same idnum
1934   // but if we refresh the methods array, the counts will be wrong.
1935   ResourceMark rm(THREAD);
1936   GrowableArray<int>* idnums = new GrowableArray<int>(methods_length);
1937   int num_methods = 0;
1938 
1939   for (int i = 0; i < methods_length; i++) {
1940     methodHandle method(THREAD, methods->at(i));
1941     if (select_method(method, want_constructor)) {
1942       if (!publicOnly || method->is_public()) {
1943         idnums->push(method->method_idnum());
1944         ++num_methods;
1945       }
1946     }
1947   }
1948 
1949   // Allocate result
1950   objArrayOop r = oopFactory::new_objArray(klass, num_methods, CHECK_NULL);
1951   objArrayHandle result (THREAD, r);
1952 
1953   // Now just put the methods that we selected above, but go by their idnum
1954   // in case of redefinition.  The methods can be redefined at any safepoint,
1955   // so above when allocating the oop array and below when creating reflect
1956   // objects.
1957   for (int i = 0; i < num_methods; i++) {
1958     methodHandle method(THREAD, k->method_with_idnum(idnums->at(i)));
1959     if (method.is_null()) {
1960       // Method may have been deleted and seems this API can handle null
1961       // Otherwise should probably put a method that throws NSME
1962       result->obj_at_put(i, NULL);
1963     } else {
1964       oop m;
1965       if (want_constructor) {
1966         m = Reflection::new_constructor(method, CHECK_NULL);
1967       } else {
1968         m = Reflection::new_method(method, false, CHECK_NULL);
1969       }
1970       result->obj_at_put(i, m);
1971     }
1972   }
1973 
1974   return (jobjectArray) JNIHandles::make_local(env, result());
1975 }
1976 
1977 JVM_ENTRY(jobjectArray, JVM_GetClassDeclaredMethods(JNIEnv *env, jclass ofClass, jboolean publicOnly))
1978 {
1979   JVMWrapper("JVM_GetClassDeclaredMethods");
1980   return get_class_declared_methods_helper(env, ofClass, publicOnly,
1981                                            /*want_constructor*/ false,
1982                                            SystemDictionary::reflect_Method_klass(), THREAD);
1983 }
1984 JVM_END
1985 
1986 JVM_ENTRY(jobjectArray, JVM_GetClassDeclaredConstructors(JNIEnv *env, jclass ofClass, jboolean publicOnly))
1987 {
1988   JVMWrapper("JVM_GetClassDeclaredConstructors");
1989   return get_class_declared_methods_helper(env, ofClass, publicOnly,
1990                                            /*want_constructor*/ true,
1991                                            SystemDictionary::reflect_Constructor_klass(), THREAD);
1992 }
1993 JVM_END
1994 
1995 JVM_ENTRY(jint, JVM_GetClassAccessFlags(JNIEnv *env, jclass cls))
1996 {
1997   JVMWrapper("JVM_GetClassAccessFlags");
1998   if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(cls))) {
1999     // Primitive type
2000     return JVM_ACC_ABSTRACT | JVM_ACC_FINAL | JVM_ACC_PUBLIC;
2001   }
2002 
2003   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2004   return k->access_flags().as_int() & JVM_ACC_WRITTEN_FLAGS;
2005 }
2006 JVM_END
2007 
2008 
2009 // Constant pool access //////////////////////////////////////////////////////////
2010 
2011 JVM_ENTRY(jobject, JVM_GetClassConstantPool(JNIEnv *env, jclass cls))
2012 {
2013   JVMWrapper("JVM_GetClassConstantPool");
2014   JvmtiVMObjectAllocEventCollector oam;
2015 
2016   // Return null for primitives and arrays
2017   if (!java_lang_Class::is_primitive(JNIHandles::resolve_non_null(cls))) {
2018     Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2019     if (k->oop_is_instance()) {
2020       instanceKlassHandle k_h(THREAD, k);
2021       Handle jcp = sun_reflect_ConstantPool::create(CHECK_NULL);
2022       sun_reflect_ConstantPool::set_cp(jcp(), k_h->constants());
2023       return JNIHandles::make_local(jcp());
2024     }
2025   }
2026   return NULL;
2027 }
2028 JVM_END
2029 
2030 
2031 JVM_ENTRY(jint, JVM_ConstantPoolGetSize(JNIEnv *env, jobject obj, jobject unused))
2032 {
2033   JVMWrapper("JVM_ConstantPoolGetSize");
2034   constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2035   return cp->length();
2036 }
2037 JVM_END
2038 
2039 
2040 JVM_ENTRY(jclass, JVM_ConstantPoolGetClassAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2041 {
2042   JVMWrapper("JVM_ConstantPoolGetClassAt");
2043   constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2044   bounds_check(cp, index, CHECK_NULL);
2045   constantTag tag = cp->tag_at(index);
2046   if (!tag.is_klass() && !tag.is_unresolved_klass()) {
2047     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2048   }
2049   Klass* k = cp->klass_at(index, CHECK_NULL);
2050   return (jclass) JNIHandles::make_local(k->java_mirror());
2051 }
2052 JVM_END
2053 
2054 JVM_ENTRY(jclass, JVM_ConstantPoolGetClassAtIfLoaded(JNIEnv *env, jobject obj, jobject unused, jint index))
2055 {
2056   JVMWrapper("JVM_ConstantPoolGetClassAtIfLoaded");
2057   constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2058   bounds_check(cp, index, CHECK_NULL);
2059   constantTag tag = cp->tag_at(index);
2060   if (!tag.is_klass() && !tag.is_unresolved_klass()) {
2061     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2062   }
2063   Klass* k = ConstantPool::klass_at_if_loaded(cp, index);
2064   if (k == NULL) return NULL;
2065   return (jclass) JNIHandles::make_local(k->java_mirror());
2066 }
2067 JVM_END
2068 
2069 static jobject get_method_at_helper(constantPoolHandle cp, jint index, bool force_resolution, TRAPS) {
2070   constantTag tag = cp->tag_at(index);
2071   if (!tag.is_method() && !tag.is_interface_method()) {
2072     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2073   }
2074   int klass_ref  = cp->uncached_klass_ref_index_at(index);
2075   Klass* k_o;
2076   if (force_resolution) {
2077     k_o = cp->klass_at(klass_ref, CHECK_NULL);
2078   } else {
2079     k_o = ConstantPool::klass_at_if_loaded(cp, klass_ref);
2080     if (k_o == NULL) return NULL;
2081   }
2082   instanceKlassHandle k(THREAD, k_o);
2083   Symbol* name = cp->uncached_name_ref_at(index);
2084   Symbol* sig  = cp->uncached_signature_ref_at(index);
2085   methodHandle m (THREAD, k->find_method(name, sig));
2086   if (m.is_null()) {
2087     THROW_MSG_0(vmSymbols::java_lang_RuntimeException(), "Unable to look up method in target class");
2088   }
2089   oop method;
2090   if (!m->is_initializer() || m->is_static()) {
2091     method = Reflection::new_method(m, true, CHECK_NULL);
2092   } else {
2093     method = Reflection::new_constructor(m, CHECK_NULL);
2094   }
2095   return JNIHandles::make_local(method);
2096 }
2097 
2098 JVM_ENTRY(jobject, JVM_ConstantPoolGetMethodAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2099 {
2100   JVMWrapper("JVM_ConstantPoolGetMethodAt");
2101   JvmtiVMObjectAllocEventCollector oam;
2102   constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2103   bounds_check(cp, index, CHECK_NULL);
2104   jobject res = get_method_at_helper(cp, index, true, CHECK_NULL);
2105   return res;
2106 }
2107 JVM_END
2108 
2109 JVM_ENTRY(jobject, JVM_ConstantPoolGetMethodAtIfLoaded(JNIEnv *env, jobject obj, jobject unused, jint index))
2110 {
2111   JVMWrapper("JVM_ConstantPoolGetMethodAtIfLoaded");
2112   JvmtiVMObjectAllocEventCollector oam;
2113   constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2114   bounds_check(cp, index, CHECK_NULL);
2115   jobject res = get_method_at_helper(cp, index, false, CHECK_NULL);
2116   return res;
2117 }
2118 JVM_END
2119 
2120 static jobject get_field_at_helper(constantPoolHandle cp, jint index, bool force_resolution, TRAPS) {
2121   constantTag tag = cp->tag_at(index);
2122   if (!tag.is_field()) {
2123     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2124   }
2125   int klass_ref  = cp->uncached_klass_ref_index_at(index);
2126   Klass* k_o;
2127   if (force_resolution) {
2128     k_o = cp->klass_at(klass_ref, CHECK_NULL);
2129   } else {
2130     k_o = ConstantPool::klass_at_if_loaded(cp, klass_ref);
2131     if (k_o == NULL) return NULL;
2132   }
2133   instanceKlassHandle k(THREAD, k_o);
2134   Symbol* name = cp->uncached_name_ref_at(index);
2135   Symbol* sig  = cp->uncached_signature_ref_at(index);
2136   fieldDescriptor fd;
2137   Klass* target_klass = k->find_field(name, sig, &fd);
2138   if (target_klass == NULL) {
2139     THROW_MSG_0(vmSymbols::java_lang_RuntimeException(), "Unable to look up field in target class");
2140   }
2141   oop field = Reflection::new_field(&fd, CHECK_NULL);
2142   return JNIHandles::make_local(field);
2143 }
2144 
2145 JVM_ENTRY(jobject, JVM_ConstantPoolGetFieldAt(JNIEnv *env, jobject obj, jobject unusedl, jint index))
2146 {
2147   JVMWrapper("JVM_ConstantPoolGetFieldAt");
2148   JvmtiVMObjectAllocEventCollector oam;
2149   constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2150   bounds_check(cp, index, CHECK_NULL);
2151   jobject res = get_field_at_helper(cp, index, true, CHECK_NULL);
2152   return res;
2153 }
2154 JVM_END
2155 
2156 JVM_ENTRY(jobject, JVM_ConstantPoolGetFieldAtIfLoaded(JNIEnv *env, jobject obj, jobject unused, jint index))
2157 {
2158   JVMWrapper("JVM_ConstantPoolGetFieldAtIfLoaded");
2159   JvmtiVMObjectAllocEventCollector oam;
2160   constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2161   bounds_check(cp, index, CHECK_NULL);
2162   jobject res = get_field_at_helper(cp, index, false, CHECK_NULL);
2163   return res;
2164 }
2165 JVM_END
2166 
2167 JVM_ENTRY(jobjectArray, JVM_ConstantPoolGetMemberRefInfoAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2168 {
2169   JVMWrapper("JVM_ConstantPoolGetMemberRefInfoAt");
2170   JvmtiVMObjectAllocEventCollector oam;
2171   constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2172   bounds_check(cp, index, CHECK_NULL);
2173   constantTag tag = cp->tag_at(index);
2174   if (!tag.is_field_or_method()) {
2175     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2176   }
2177   int klass_ref = cp->uncached_klass_ref_index_at(index);
2178   Symbol*  klass_name  = cp->klass_name_at(klass_ref);
2179   Symbol*  member_name = cp->uncached_name_ref_at(index);
2180   Symbol*  member_sig  = cp->uncached_signature_ref_at(index);
2181   objArrayOop  dest_o = oopFactory::new_objArray(SystemDictionary::String_klass(), 3, CHECK_NULL);
2182   objArrayHandle dest(THREAD, dest_o);
2183   Handle str = java_lang_String::create_from_symbol(klass_name, CHECK_NULL);
2184   dest->obj_at_put(0, str());
2185   str = java_lang_String::create_from_symbol(member_name, CHECK_NULL);
2186   dest->obj_at_put(1, str());
2187   str = java_lang_String::create_from_symbol(member_sig, CHECK_NULL);
2188   dest->obj_at_put(2, str());
2189   return (jobjectArray) JNIHandles::make_local(dest());
2190 }
2191 JVM_END
2192 
2193 JVM_ENTRY(jint, JVM_ConstantPoolGetIntAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2194 {
2195   JVMWrapper("JVM_ConstantPoolGetIntAt");
2196   constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2197   bounds_check(cp, index, CHECK_0);
2198   constantTag tag = cp->tag_at(index);
2199   if (!tag.is_int()) {
2200     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2201   }
2202   return cp->int_at(index);
2203 }
2204 JVM_END
2205 
2206 JVM_ENTRY(jlong, JVM_ConstantPoolGetLongAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2207 {
2208   JVMWrapper("JVM_ConstantPoolGetLongAt");
2209   constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2210   bounds_check(cp, index, CHECK_(0L));
2211   constantTag tag = cp->tag_at(index);
2212   if (!tag.is_long()) {
2213     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2214   }
2215   return cp->long_at(index);
2216 }
2217 JVM_END
2218 
2219 JVM_ENTRY(jfloat, JVM_ConstantPoolGetFloatAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2220 {
2221   JVMWrapper("JVM_ConstantPoolGetFloatAt");
2222   constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2223   bounds_check(cp, index, CHECK_(0.0f));
2224   constantTag tag = cp->tag_at(index);
2225   if (!tag.is_float()) {
2226     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2227   }
2228   return cp->float_at(index);
2229 }
2230 JVM_END
2231 
2232 JVM_ENTRY(jdouble, JVM_ConstantPoolGetDoubleAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2233 {
2234   JVMWrapper("JVM_ConstantPoolGetDoubleAt");
2235   constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2236   bounds_check(cp, index, CHECK_(0.0));
2237   constantTag tag = cp->tag_at(index);
2238   if (!tag.is_double()) {
2239     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2240   }
2241   return cp->double_at(index);
2242 }
2243 JVM_END
2244 
2245 JVM_ENTRY(jstring, JVM_ConstantPoolGetStringAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2246 {
2247   JVMWrapper("JVM_ConstantPoolGetStringAt");
2248   constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2249   bounds_check(cp, index, CHECK_NULL);
2250   constantTag tag = cp->tag_at(index);
2251   if (!tag.is_string()) {
2252     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2253   }
2254   oop str = cp->string_at(index, CHECK_NULL);
2255   return (jstring) JNIHandles::make_local(str);
2256 }
2257 JVM_END
2258 
2259 JVM_ENTRY(jstring, JVM_ConstantPoolGetUTF8At(JNIEnv *env, jobject obj, jobject unused, jint index))
2260 {
2261   JVMWrapper("JVM_ConstantPoolGetUTF8At");
2262   JvmtiVMObjectAllocEventCollector oam;
2263   constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2264   bounds_check(cp, index, CHECK_NULL);
2265   constantTag tag = cp->tag_at(index);
2266   if (!tag.is_symbol()) {
2267     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2268   }
2269   Symbol* sym = cp->symbol_at(index);
2270   Handle str = java_lang_String::create_from_symbol(sym, CHECK_NULL);
2271   return (jstring) JNIHandles::make_local(str());
2272 }
2273 JVM_END
2274 
2275 
2276 // Assertion support. //////////////////////////////////////////////////////////
2277 
2278 JVM_ENTRY(jboolean, JVM_DesiredAssertionStatus(JNIEnv *env, jclass unused, jclass cls))
2279   JVMWrapper("JVM_DesiredAssertionStatus");
2280   assert(cls != NULL, "bad class");
2281 
2282   oop r = JNIHandles::resolve(cls);
2283   assert(! java_lang_Class::is_primitive(r), "primitive classes not allowed");
2284   if (java_lang_Class::is_primitive(r)) return false;
2285 
2286   Klass* k = java_lang_Class::as_Klass(r);
2287   assert(k->oop_is_instance(), "must be an instance klass");
2288   if (! k->oop_is_instance()) return false;
2289 
2290   ResourceMark rm(THREAD);
2291   const char* name = k->name()->as_C_string();
2292   bool system_class = k->class_loader() == NULL;
2293   return JavaAssertions::enabled(name, system_class);
2294 
2295 JVM_END
2296 
2297 
2298 // Return a new AssertionStatusDirectives object with the fields filled in with
2299 // command-line assertion arguments (i.e., -ea, -da).
2300 JVM_ENTRY(jobject, JVM_AssertionStatusDirectives(JNIEnv *env, jclass unused))
2301   JVMWrapper("JVM_AssertionStatusDirectives");
2302   JvmtiVMObjectAllocEventCollector oam;
2303   oop asd = JavaAssertions::createAssertionStatusDirectives(CHECK_NULL);
2304   return JNIHandles::make_local(env, asd);
2305 JVM_END
2306 
2307 // Verification ////////////////////////////////////////////////////////////////////////////////
2308 
2309 // Reflection for the verifier /////////////////////////////////////////////////////////////////
2310 
2311 // RedefineClasses support: bug 6214132 caused verification to fail.
2312 // All functions from this section should call the jvmtiThreadSate function:
2313 //   Klass* class_to_verify_considering_redefinition(Klass* klass).
2314 // The function returns a Klass* of the _scratch_class if the verifier
2315 // was invoked in the middle of the class redefinition.
2316 // Otherwise it returns its argument value which is the _the_class Klass*.
2317 // Please, refer to the description in the jvmtiThreadSate.hpp.
2318 
2319 JVM_ENTRY(const char*, JVM_GetClassNameUTF(JNIEnv *env, jclass cls))
2320   JVMWrapper("JVM_GetClassNameUTF");
2321   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2322   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2323   return k->name()->as_utf8();
2324 JVM_END
2325 
2326 
2327 JVM_QUICK_ENTRY(void, JVM_GetClassCPTypes(JNIEnv *env, jclass cls, unsigned char *types))
2328   JVMWrapper("JVM_GetClassCPTypes");
2329   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2330   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2331   // types will have length zero if this is not an InstanceKlass
2332   // (length is determined by call to JVM_GetClassCPEntriesCount)
2333   if (k->oop_is_instance()) {
2334     ConstantPool* cp = InstanceKlass::cast(k)->constants();
2335     for (int index = cp->length() - 1; index >= 0; index--) {
2336       constantTag tag = cp->tag_at(index);
2337       types[index] = (tag.is_unresolved_klass()) ? JVM_CONSTANT_Class : tag.value();
2338   }
2339   }
2340 JVM_END
2341 
2342 
2343 JVM_QUICK_ENTRY(jint, JVM_GetClassCPEntriesCount(JNIEnv *env, jclass cls))
2344   JVMWrapper("JVM_GetClassCPEntriesCount");
2345   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2346   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2347   if (!k->oop_is_instance())
2348     return 0;
2349   return InstanceKlass::cast(k)->constants()->length();
2350 JVM_END
2351 
2352 
2353 JVM_QUICK_ENTRY(jint, JVM_GetClassFieldsCount(JNIEnv *env, jclass cls))
2354   JVMWrapper("JVM_GetClassFieldsCount");
2355   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2356   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2357   if (!k->oop_is_instance())
2358     return 0;
2359   return InstanceKlass::cast(k)->java_fields_count();
2360 JVM_END
2361 
2362 
2363 JVM_QUICK_ENTRY(jint, JVM_GetClassMethodsCount(JNIEnv *env, jclass cls))
2364   JVMWrapper("JVM_GetClassMethodsCount");
2365   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2366   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2367   if (!k->oop_is_instance())
2368     return 0;
2369   return InstanceKlass::cast(k)->methods()->length();
2370 JVM_END
2371 
2372 
2373 // The following methods, used for the verifier, are never called with
2374 // array klasses, so a direct cast to InstanceKlass is safe.
2375 // Typically, these methods are called in a loop with bounds determined
2376 // by the results of JVM_GetClass{Fields,Methods}Count, which return
2377 // zero for arrays.
2378 JVM_QUICK_ENTRY(void, JVM_GetMethodIxExceptionIndexes(JNIEnv *env, jclass cls, jint method_index, unsigned short *exceptions))
2379   JVMWrapper("JVM_GetMethodIxExceptionIndexes");
2380   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2381   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2382   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2383   int length = method->checked_exceptions_length();
2384   if (length > 0) {
2385     CheckedExceptionElement* table= method->checked_exceptions_start();
2386     for (int i = 0; i < length; i++) {
2387       exceptions[i] = table[i].class_cp_index;
2388     }
2389   }
2390 JVM_END
2391 
2392 
2393 JVM_QUICK_ENTRY(jint, JVM_GetMethodIxExceptionsCount(JNIEnv *env, jclass cls, jint method_index))
2394   JVMWrapper("JVM_GetMethodIxExceptionsCount");
2395   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2396   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2397   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2398   return method->checked_exceptions_length();
2399 JVM_END
2400 
2401 
2402 JVM_QUICK_ENTRY(void, JVM_GetMethodIxByteCode(JNIEnv *env, jclass cls, jint method_index, unsigned char *code))
2403   JVMWrapper("JVM_GetMethodIxByteCode");
2404   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2405   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2406   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2407   memcpy(code, method->code_base(), method->code_size());
2408 JVM_END
2409 
2410 
2411 JVM_QUICK_ENTRY(jint, JVM_GetMethodIxByteCodeLength(JNIEnv *env, jclass cls, jint method_index))
2412   JVMWrapper("JVM_GetMethodIxByteCodeLength");
2413   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2414   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2415   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2416   return method->code_size();
2417 JVM_END
2418 
2419 
2420 JVM_QUICK_ENTRY(void, JVM_GetMethodIxExceptionTableEntry(JNIEnv *env, jclass cls, jint method_index, jint entry_index, JVM_ExceptionTableEntryType *entry))
2421   JVMWrapper("JVM_GetMethodIxExceptionTableEntry");
2422   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2423   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2424   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2425   ExceptionTable extable(method);
2426   entry->start_pc   = extable.start_pc(entry_index);
2427   entry->end_pc     = extable.end_pc(entry_index);
2428   entry->handler_pc = extable.handler_pc(entry_index);
2429   entry->catchType  = extable.catch_type_index(entry_index);
2430 JVM_END
2431 
2432 
2433 JVM_QUICK_ENTRY(jint, JVM_GetMethodIxExceptionTableLength(JNIEnv *env, jclass cls, int method_index))
2434   JVMWrapper("JVM_GetMethodIxExceptionTableLength");
2435   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2436   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2437   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2438   return method->exception_table_length();
2439 JVM_END
2440 
2441 
2442 JVM_QUICK_ENTRY(jint, JVM_GetMethodIxModifiers(JNIEnv *env, jclass cls, int method_index))
2443   JVMWrapper("JVM_GetMethodIxModifiers");
2444   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2445   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2446   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2447   return method->access_flags().as_int() & JVM_RECOGNIZED_METHOD_MODIFIERS;
2448 JVM_END
2449 
2450 
2451 JVM_QUICK_ENTRY(jint, JVM_GetFieldIxModifiers(JNIEnv *env, jclass cls, int field_index))
2452   JVMWrapper("JVM_GetFieldIxModifiers");
2453   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2454   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2455   return InstanceKlass::cast(k)->field_access_flags(field_index) & JVM_RECOGNIZED_FIELD_MODIFIERS;
2456 JVM_END
2457 
2458 
2459 JVM_QUICK_ENTRY(jint, JVM_GetMethodIxLocalsCount(JNIEnv *env, jclass cls, int method_index))
2460   JVMWrapper("JVM_GetMethodIxLocalsCount");
2461   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2462   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2463   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2464   return method->max_locals();
2465 JVM_END
2466 
2467 
2468 JVM_QUICK_ENTRY(jint, JVM_GetMethodIxArgsSize(JNIEnv *env, jclass cls, int method_index))
2469   JVMWrapper("JVM_GetMethodIxArgsSize");
2470   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2471   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2472   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2473   return method->size_of_parameters();
2474 JVM_END
2475 
2476 
2477 JVM_QUICK_ENTRY(jint, JVM_GetMethodIxMaxStack(JNIEnv *env, jclass cls, int method_index))
2478   JVMWrapper("JVM_GetMethodIxMaxStack");
2479   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2480   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2481   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2482   return method->verifier_max_stack();
2483 JVM_END
2484 
2485 
2486 JVM_QUICK_ENTRY(jboolean, JVM_IsConstructorIx(JNIEnv *env, jclass cls, int method_index))
2487   JVMWrapper("JVM_IsConstructorIx");
2488   ResourceMark rm(THREAD);
2489   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2490   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2491   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2492   return method->name() == vmSymbols::object_initializer_name();
2493 JVM_END
2494 
2495 
2496 JVM_QUICK_ENTRY(jboolean, JVM_IsVMGeneratedMethodIx(JNIEnv *env, jclass cls, int method_index))
2497   JVMWrapper("JVM_IsVMGeneratedMethodIx");
2498   ResourceMark rm(THREAD);
2499   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2500   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2501   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2502   return method->is_overpass();
2503 JVM_END
2504 
2505 JVM_ENTRY(const char*, JVM_GetMethodIxNameUTF(JNIEnv *env, jclass cls, jint method_index))
2506   JVMWrapper("JVM_GetMethodIxIxUTF");
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->name()->as_utf8();
2511 JVM_END
2512 
2513 
2514 JVM_ENTRY(const char*, JVM_GetMethodIxSignatureUTF(JNIEnv *env, jclass cls, jint method_index))
2515   JVMWrapper("JVM_GetMethodIxSignatureUTF");
2516   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2517   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2518   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2519   return method->signature()->as_utf8();
2520 JVM_END
2521 
2522 /**
2523  * All of these JVM_GetCP-xxx methods are used by the old verifier to
2524  * read entries in the constant pool.  Since the old verifier always
2525  * works on a copy of the code, it will not see any rewriting that
2526  * may possibly occur in the middle of verification.  So it is important
2527  * that nothing it calls tries to use the cpCache instead of the raw
2528  * constant pool, so we must use cp->uncached_x methods when appropriate.
2529  */
2530 JVM_ENTRY(const char*, JVM_GetCPFieldNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2531   JVMWrapper("JVM_GetCPFieldNameUTF");
2532   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2533   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2534   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2535   switch (cp->tag_at(cp_index).value()) {
2536     case JVM_CONSTANT_Fieldref:
2537       return cp->uncached_name_ref_at(cp_index)->as_utf8();
2538     default:
2539       fatal("JVM_GetCPFieldNameUTF: illegal constant");
2540   }
2541   ShouldNotReachHere();
2542   return NULL;
2543 JVM_END
2544 
2545 
2546 JVM_ENTRY(const char*, JVM_GetCPMethodNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2547   JVMWrapper("JVM_GetCPMethodNameUTF");
2548   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2549   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2550   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2551   switch (cp->tag_at(cp_index).value()) {
2552     case JVM_CONSTANT_InterfaceMethodref:
2553     case JVM_CONSTANT_Methodref:
2554     case JVM_CONSTANT_NameAndType:  // for invokedynamic
2555       return cp->uncached_name_ref_at(cp_index)->as_utf8();
2556     default:
2557       fatal("JVM_GetCPMethodNameUTF: illegal constant");
2558   }
2559   ShouldNotReachHere();
2560   return NULL;
2561 JVM_END
2562 
2563 
2564 JVM_ENTRY(const char*, JVM_GetCPMethodSignatureUTF(JNIEnv *env, jclass cls, jint cp_index))
2565   JVMWrapper("JVM_GetCPMethodSignatureUTF");
2566   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2567   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2568   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2569   switch (cp->tag_at(cp_index).value()) {
2570     case JVM_CONSTANT_InterfaceMethodref:
2571     case JVM_CONSTANT_Methodref:
2572     case JVM_CONSTANT_NameAndType:  // for invokedynamic
2573       return cp->uncached_signature_ref_at(cp_index)->as_utf8();
2574     default:
2575       fatal("JVM_GetCPMethodSignatureUTF: illegal constant");
2576   }
2577   ShouldNotReachHere();
2578   return NULL;
2579 JVM_END
2580 
2581 
2582 JVM_ENTRY(const char*, JVM_GetCPFieldSignatureUTF(JNIEnv *env, jclass cls, jint cp_index))
2583   JVMWrapper("JVM_GetCPFieldSignatureUTF");
2584   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2585   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2586   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2587   switch (cp->tag_at(cp_index).value()) {
2588     case JVM_CONSTANT_Fieldref:
2589       return cp->uncached_signature_ref_at(cp_index)->as_utf8();
2590     default:
2591       fatal("JVM_GetCPFieldSignatureUTF: illegal constant");
2592   }
2593   ShouldNotReachHere();
2594   return NULL;
2595 JVM_END
2596 
2597 
2598 JVM_ENTRY(const char*, JVM_GetCPClassNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2599   JVMWrapper("JVM_GetCPClassNameUTF");
2600   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2601   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2602   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2603   Symbol* classname = cp->klass_name_at(cp_index);
2604   return classname->as_utf8();
2605 JVM_END
2606 
2607 
2608 JVM_ENTRY(const char*, JVM_GetCPFieldClassNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2609   JVMWrapper("JVM_GetCPFieldClassNameUTF");
2610   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2611   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2612   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2613   switch (cp->tag_at(cp_index).value()) {
2614     case JVM_CONSTANT_Fieldref: {
2615       int class_index = cp->uncached_klass_ref_index_at(cp_index);
2616       Symbol* classname = cp->klass_name_at(class_index);
2617       return classname->as_utf8();
2618     }
2619     default:
2620       fatal("JVM_GetCPFieldClassNameUTF: illegal constant");
2621   }
2622   ShouldNotReachHere();
2623   return NULL;
2624 JVM_END
2625 
2626 
2627 JVM_ENTRY(const char*, JVM_GetCPMethodClassNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2628   JVMWrapper("JVM_GetCPMethodClassNameUTF");
2629   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2630   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2631   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2632   switch (cp->tag_at(cp_index).value()) {
2633     case JVM_CONSTANT_Methodref:
2634     case JVM_CONSTANT_InterfaceMethodref: {
2635       int class_index = cp->uncached_klass_ref_index_at(cp_index);
2636       Symbol* classname = cp->klass_name_at(class_index);
2637       return classname->as_utf8();
2638     }
2639     default:
2640       fatal("JVM_GetCPMethodClassNameUTF: illegal constant");
2641   }
2642   ShouldNotReachHere();
2643   return NULL;
2644 JVM_END
2645 
2646 
2647 JVM_ENTRY(jint, JVM_GetCPFieldModifiers(JNIEnv *env, jclass cls, int cp_index, jclass called_cls))
2648   JVMWrapper("JVM_GetCPFieldModifiers");
2649   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2650   Klass* k_called = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(called_cls));
2651   k        = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2652   k_called = JvmtiThreadState::class_to_verify_considering_redefinition(k_called, thread);
2653   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2654   ConstantPool* cp_called = InstanceKlass::cast(k_called)->constants();
2655   switch (cp->tag_at(cp_index).value()) {
2656     case JVM_CONSTANT_Fieldref: {
2657       Symbol* name      = cp->uncached_name_ref_at(cp_index);
2658       Symbol* signature = cp->uncached_signature_ref_at(cp_index);
2659       for (JavaFieldStream fs(k_called); !fs.done(); fs.next()) {
2660         if (fs.name() == name && fs.signature() == signature) {
2661           return fs.access_flags().as_short() & JVM_RECOGNIZED_FIELD_MODIFIERS;
2662         }
2663       }
2664       return -1;
2665     }
2666     default:
2667       fatal("JVM_GetCPFieldModifiers: illegal constant");
2668   }
2669   ShouldNotReachHere();
2670   return 0;
2671 JVM_END
2672 
2673 
2674 JVM_QUICK_ENTRY(jint, JVM_GetCPMethodModifiers(JNIEnv *env, jclass cls, int cp_index, jclass called_cls))
2675   JVMWrapper("JVM_GetCPMethodModifiers");
2676   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2677   Klass* k_called = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(called_cls));
2678   k        = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2679   k_called = JvmtiThreadState::class_to_verify_considering_redefinition(k_called, thread);
2680   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2681   switch (cp->tag_at(cp_index).value()) {
2682     case JVM_CONSTANT_Methodref:
2683     case JVM_CONSTANT_InterfaceMethodref: {
2684       Symbol* name      = cp->uncached_name_ref_at(cp_index);
2685       Symbol* signature = cp->uncached_signature_ref_at(cp_index);
2686       Array<Method*>* methods = InstanceKlass::cast(k_called)->methods();
2687       int methods_count = methods->length();
2688       for (int i = 0; i < methods_count; i++) {
2689         Method* method = methods->at(i);
2690         if (method->name() == name && method->signature() == signature) {
2691             return method->access_flags().as_int() & JVM_RECOGNIZED_METHOD_MODIFIERS;
2692         }
2693       }
2694       return -1;
2695     }
2696     default:
2697       fatal("JVM_GetCPMethodModifiers: illegal constant");
2698   }
2699   ShouldNotReachHere();
2700   return 0;
2701 JVM_END
2702 
2703 
2704 // Misc //////////////////////////////////////////////////////////////////////////////////////////////
2705 
2706 JVM_LEAF(void, JVM_ReleaseUTF(const char *utf))
2707   // So long as UTF8::convert_to_utf8 returns resource strings, we don't have to do anything
2708 JVM_END
2709 
2710 
2711 JVM_ENTRY(jboolean, JVM_IsSameClassPackage(JNIEnv *env, jclass class1, jclass class2))
2712   JVMWrapper("JVM_IsSameClassPackage");
2713   oop class1_mirror = JNIHandles::resolve_non_null(class1);
2714   oop class2_mirror = JNIHandles::resolve_non_null(class2);
2715   Klass* klass1 = java_lang_Class::as_Klass(class1_mirror);
2716   Klass* klass2 = java_lang_Class::as_Klass(class2_mirror);
2717   return (jboolean) Reflection::is_same_class_package(klass1, klass2);
2718 JVM_END
2719 
2720 
2721 // IO functions ////////////////////////////////////////////////////////////////////////////////////////
2722 
2723 JVM_LEAF(jint, JVM_Open(const char *fname, jint flags, jint mode))
2724   JVMWrapper2("JVM_Open (%s)", fname);
2725 
2726   //%note jvm_r6
2727   int result = os::open(fname, flags, mode);
2728   if (result >= 0) {
2729     return result;
2730   } else {
2731     switch(errno) {
2732       case EEXIST:
2733         return JVM_EEXIST;
2734       default:
2735         return -1;
2736     }
2737   }
2738 JVM_END
2739 
2740 
2741 JVM_LEAF(jint, JVM_Close(jint fd))
2742   JVMWrapper2("JVM_Close (0x%x)", fd);
2743   //%note jvm_r6
2744   return os::close(fd);
2745 JVM_END
2746 
2747 
2748 JVM_LEAF(jint, JVM_Read(jint fd, char *buf, jint nbytes))
2749   JVMWrapper2("JVM_Read (0x%x)", fd);
2750 
2751   //%note jvm_r6
2752   return (jint)os::restartable_read(fd, buf, nbytes);
2753 JVM_END
2754 
2755 
2756 JVM_LEAF(jint, JVM_Write(jint fd, char *buf, jint nbytes))
2757   JVMWrapper2("JVM_Write (0x%x)", fd);
2758 
2759   //%note jvm_r6
2760   return (jint)os::write(fd, buf, nbytes);
2761 JVM_END
2762 
2763 
2764 JVM_LEAF(jint, JVM_Available(jint fd, jlong *pbytes))
2765   JVMWrapper2("JVM_Available (0x%x)", fd);
2766   //%note jvm_r6
2767   return os::available(fd, pbytes);
2768 JVM_END
2769 
2770 
2771 JVM_LEAF(jlong, JVM_Lseek(jint fd, jlong offset, jint whence))
2772   JVMWrapper4("JVM_Lseek (0x%x, " INT64_FORMAT ", %d)", fd, (int64_t) offset, whence);
2773   //%note jvm_r6
2774   return os::lseek(fd, offset, whence);
2775 JVM_END
2776 
2777 
2778 JVM_LEAF(jint, JVM_SetLength(jint fd, jlong length))
2779   JVMWrapper3("JVM_SetLength (0x%x, " INT64_FORMAT ")", fd, (int64_t) length);
2780   return os::ftruncate(fd, length);
2781 JVM_END
2782 
2783 
2784 JVM_LEAF(jint, JVM_Sync(jint fd))
2785   JVMWrapper2("JVM_Sync (0x%x)", fd);
2786   //%note jvm_r6
2787   return os::fsync(fd);
2788 JVM_END
2789 
2790 
2791 // Printing support //////////////////////////////////////////////////
2792 extern "C" {
2793 
2794 ATTRIBUTE_PRINTF(3, 0)
2795 int jio_vsnprintf(char *str, size_t count, const char *fmt, va_list args) {
2796   // see bug 4399518, 4417214
2797   if ((intptr_t)count <= 0) return -1;
2798   return vsnprintf(str, count, fmt, args);
2799 }
2800 
2801 ATTRIBUTE_PRINTF(3, 0)
2802 int jio_snprintf(char *str, size_t count, const char *fmt, ...) {
2803   va_list args;
2804   int len;
2805   va_start(args, fmt);
2806   len = jio_vsnprintf(str, count, fmt, args);
2807   va_end(args);
2808   return len;
2809 }
2810 
2811 ATTRIBUTE_PRINTF(2,3)
2812 int jio_fprintf(FILE* f, const char *fmt, ...) {
2813   int len;
2814   va_list args;
2815   va_start(args, fmt);
2816   len = jio_vfprintf(f, fmt, args);
2817   va_end(args);
2818   return len;
2819 }
2820 
2821 ATTRIBUTE_PRINTF(2, 0)
2822 int jio_vfprintf(FILE* f, const char *fmt, va_list args) {
2823   if (Arguments::vfprintf_hook() != NULL) {
2824      return Arguments::vfprintf_hook()(f, fmt, args);
2825   } else {
2826     return vfprintf(f, fmt, args);
2827   }
2828 }
2829 
2830 ATTRIBUTE_PRINTF(1, 2)
2831 JNIEXPORT int jio_printf(const char *fmt, ...) {
2832   int len;
2833   va_list args;
2834   va_start(args, fmt);
2835   len = jio_vfprintf(defaultStream::output_stream(), fmt, args);
2836   va_end(args);
2837   return len;
2838 }
2839 
2840 
2841 // HotSpot specific jio method
2842 void jio_print(const char* s) {
2843   // Try to make this function as atomic as possible.
2844   if (Arguments::vfprintf_hook() != NULL) {
2845     jio_fprintf(defaultStream::output_stream(), "%s", s);
2846   } else {
2847     // Make an unused local variable to avoid warning from gcc 4.x compiler.
2848     size_t count = ::write(defaultStream::output_fd(), s, (int)strlen(s));
2849   }
2850 }
2851 
2852 } // Extern C
2853 
2854 // java.lang.Thread //////////////////////////////////////////////////////////////////////////////
2855 
2856 // In most of the JVM Thread support functions we need to be sure to lock the Threads_lock
2857 // to prevent the target thread from exiting after we have a pointer to the C++ Thread or
2858 // OSThread objects.  The exception to this rule is when the target object is the thread
2859 // doing the operation, in which case we know that the thread won't exit until the
2860 // operation is done (all exits being voluntary).  There are a few cases where it is
2861 // rather silly to do operations on yourself, like resuming yourself or asking whether
2862 // you are alive.  While these can still happen, they are not subject to deadlocks if
2863 // the lock is held while the operation occurs (this is not the case for suspend, for
2864 // instance), and are very unlikely.  Because IsAlive needs to be fast and its
2865 // implementation is local to this file, we always lock Threads_lock for that one.
2866 
2867 static void thread_entry(JavaThread* thread, TRAPS) {
2868   HandleMark hm(THREAD);
2869   Handle obj(THREAD, thread->threadObj());
2870   JavaValue result(T_VOID);
2871   JavaCalls::call_virtual(&result,
2872                           obj,
2873                           KlassHandle(THREAD, SystemDictionary::Thread_klass()),
2874                           vmSymbols::run_method_name(),
2875                           vmSymbols::void_method_signature(),
2876                           THREAD);
2877 }
2878 
2879 
2880 JVM_ENTRY(void, JVM_StartThread(JNIEnv* env, jobject jthread))
2881   JVMWrapper("JVM_StartThread");
2882   JavaThread *native_thread = NULL;
2883 
2884   // We cannot hold the Threads_lock when we throw an exception,
2885   // due to rank ordering issues. Example:  we might need to grab the
2886   // Heap_lock while we construct the exception.
2887   bool throw_illegal_thread_state = false;
2888 
2889   // We must release the Threads_lock before we can post a jvmti event
2890   // in Thread::start.
2891   {
2892     // Ensure that the C++ Thread and OSThread structures aren't freed before
2893     // we operate.
2894     MutexLocker mu(Threads_lock);
2895 
2896     // Since JDK 5 the java.lang.Thread threadStatus is used to prevent
2897     // re-starting an already started thread, so we should usually find
2898     // that the JavaThread is null. However for a JNI attached thread
2899     // there is a small window between the Thread object being created
2900     // (with its JavaThread set) and the update to its threadStatus, so we
2901     // have to check for this
2902     if (java_lang_Thread::thread(JNIHandles::resolve_non_null(jthread)) != NULL) {
2903       throw_illegal_thread_state = true;
2904     } else {
2905       // We could also check the stillborn flag to see if this thread was already stopped, but
2906       // for historical reasons we let the thread detect that itself when it starts running
2907 
2908       jlong size =
2909              java_lang_Thread::stackSize(JNIHandles::resolve_non_null(jthread));
2910       // Allocate the C++ Thread structure and create the native thread.  The
2911       // stack size retrieved from java is signed, but the constructor takes
2912       // size_t (an unsigned type), so avoid passing negative values which would
2913       // result in really large stacks.
2914       size_t sz = size > 0 ? (size_t) size : 0;
2915       native_thread = new JavaThread(&thread_entry, sz);
2916 
2917       // At this point it may be possible that no osthread was created for the
2918       // JavaThread due to lack of memory. Check for this situation and throw
2919       // an exception if necessary. Eventually we may want to change this so
2920       // that we only grab the lock if the thread was created successfully -
2921       // then we can also do this check and throw the exception in the
2922       // JavaThread constructor.
2923       if (native_thread->osthread() != NULL) {
2924         // Note: the current thread is not being used within "prepare".
2925         native_thread->prepare(jthread);
2926       }
2927     }
2928   }
2929 
2930   if (throw_illegal_thread_state) {
2931     THROW(vmSymbols::java_lang_IllegalThreadStateException());
2932   }
2933 
2934   assert(native_thread != NULL, "Starting null thread?");
2935 
2936   if (native_thread->osthread() == NULL) {
2937     // No one should hold a reference to the 'native_thread'.
2938     delete native_thread;
2939     if (JvmtiExport::should_post_resource_exhausted()) {
2940       JvmtiExport::post_resource_exhausted(
2941         JVMTI_RESOURCE_EXHAUSTED_OOM_ERROR | JVMTI_RESOURCE_EXHAUSTED_THREADS,
2942         os::native_thread_creation_failed_msg());
2943     }
2944     THROW_MSG(vmSymbols::java_lang_OutOfMemoryError(),
2945               os::native_thread_creation_failed_msg());
2946   }
2947 
2948   Thread::start(native_thread);
2949 
2950 JVM_END
2951 
2952 // JVM_Stop is implemented using a VM_Operation, so threads are forced to safepoints
2953 // before the quasi-asynchronous exception is delivered.  This is a little obtrusive,
2954 // but is thought to be reliable and simple. In the case, where the receiver is the
2955 // same thread as the sender, no safepoint is needed.
2956 JVM_ENTRY(void, JVM_StopThread(JNIEnv* env, jobject jthread, jobject throwable))
2957   JVMWrapper("JVM_StopThread");
2958 
2959   oop java_throwable = JNIHandles::resolve(throwable);
2960   if (java_throwable == NULL) {
2961     THROW(vmSymbols::java_lang_NullPointerException());
2962   }
2963   oop java_thread = JNIHandles::resolve_non_null(jthread);
2964   JavaThread* receiver = java_lang_Thread::thread(java_thread);
2965   Events::log_exception(JavaThread::current(),
2966                         "JVM_StopThread thread JavaThread " INTPTR_FORMAT " as oop " INTPTR_FORMAT " [exception " INTPTR_FORMAT "]",
2967                         p2i(receiver), p2i((address)java_thread), p2i(throwable));
2968   // First check if thread is alive
2969   if (receiver != NULL) {
2970     // Check if exception is getting thrown at self (use oop equality, since the
2971     // target object might exit)
2972     if (java_thread == thread->threadObj()) {
2973       THROW_OOP(java_throwable);
2974     } else {
2975       // Enques a VM_Operation to stop all threads and then deliver the exception...
2976       Thread::send_async_exception(java_thread, JNIHandles::resolve(throwable));
2977     }
2978   }
2979   else {
2980     // Either:
2981     // - target thread has not been started before being stopped, or
2982     // - target thread already terminated
2983     // We could read the threadStatus to determine which case it is
2984     // but that is overkill as it doesn't matter. We must set the
2985     // stillborn flag for the first case, and if the thread has already
2986     // exited setting this flag has no affect
2987     java_lang_Thread::set_stillborn(java_thread);
2988   }
2989 JVM_END
2990 
2991 
2992 JVM_ENTRY(jboolean, JVM_IsThreadAlive(JNIEnv* env, jobject jthread))
2993   JVMWrapper("JVM_IsThreadAlive");
2994 
2995   oop thread_oop = JNIHandles::resolve_non_null(jthread);
2996   return java_lang_Thread::is_alive(thread_oop);
2997 JVM_END
2998 
2999 
3000 JVM_ENTRY(void, JVM_SuspendThread(JNIEnv* env, jobject jthread))
3001   JVMWrapper("JVM_SuspendThread");
3002   oop java_thread = JNIHandles::resolve_non_null(jthread);
3003   JavaThread* receiver = java_lang_Thread::thread(java_thread);
3004 
3005   if (receiver != NULL) {
3006     // thread has run and has not exited (still on threads list)
3007 
3008     {
3009       MutexLockerEx ml(receiver->SR_lock(), Mutex::_no_safepoint_check_flag);
3010       if (receiver->is_external_suspend()) {
3011         // Don't allow nested external suspend requests. We can't return
3012         // an error from this interface so just ignore the problem.
3013         return;
3014       }
3015       if (receiver->is_exiting()) { // thread is in the process of exiting
3016         return;
3017       }
3018       receiver->set_external_suspend();
3019     }
3020 
3021     // java_suspend() will catch threads in the process of exiting
3022     // and will ignore them.
3023     receiver->java_suspend();
3024 
3025     // It would be nice to have the following assertion in all the
3026     // time, but it is possible for a racing resume request to have
3027     // resumed this thread right after we suspended it. Temporarily
3028     // enable this assertion if you are chasing a different kind of
3029     // bug.
3030     //
3031     // assert(java_lang_Thread::thread(receiver->threadObj()) == NULL ||
3032     //   receiver->is_being_ext_suspended(), "thread is not suspended");
3033   }
3034 JVM_END
3035 
3036 
3037 JVM_ENTRY(void, JVM_ResumeThread(JNIEnv* env, jobject jthread))
3038   JVMWrapper("JVM_ResumeThread");
3039   // Ensure that the C++ Thread and OSThread structures aren't freed before we operate.
3040   // We need to *always* get the threads lock here, since this operation cannot be allowed during
3041   // a safepoint. The safepoint code relies on suspending a thread to examine its state. If other
3042   // threads randomly resumes threads, then a thread might not be suspended when the safepoint code
3043   // looks at it.
3044   MutexLocker ml(Threads_lock);
3045   JavaThread* thr = java_lang_Thread::thread(JNIHandles::resolve_non_null(jthread));
3046   if (thr != NULL) {
3047     // the thread has run and is not in the process of exiting
3048     thr->java_resume();
3049   }
3050 JVM_END
3051 
3052 
3053 JVM_ENTRY(void, JVM_SetThreadPriority(JNIEnv* env, jobject jthread, jint prio))
3054   JVMWrapper("JVM_SetThreadPriority");
3055   // Ensure that the C++ Thread and OSThread structures aren't freed before we operate
3056   MutexLocker ml(Threads_lock);
3057   oop java_thread = JNIHandles::resolve_non_null(jthread);
3058   java_lang_Thread::set_priority(java_thread, (ThreadPriority)prio);
3059   JavaThread* thr = java_lang_Thread::thread(java_thread);
3060   if (thr != NULL) {                  // Thread not yet started; priority pushed down when it is
3061     Thread::set_priority(thr, (ThreadPriority)prio);
3062   }
3063 JVM_END
3064 
3065 
3066 JVM_ENTRY(void, JVM_Yield(JNIEnv *env, jclass threadClass))
3067   JVMWrapper("JVM_Yield");
3068   if (os::dont_yield()) return;
3069   HOTSPOT_THREAD_YIELD();
3070 
3071   // When ConvertYieldToSleep is off (default), this matches the classic VM use of yield.
3072   // Critical for similar threading behaviour
3073   if (ConvertYieldToSleep) {
3074     os::sleep(thread, MinSleepInterval, false);
3075   } else {
3076     os::naked_yield();
3077   }
3078 JVM_END
3079 
3080 
3081 JVM_ENTRY(void, JVM_Sleep(JNIEnv* env, jclass threadClass, jlong millis))
3082   JVMWrapper("JVM_Sleep");
3083 
3084   if (millis < 0) {
3085     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "timeout value is negative");
3086   }
3087 
3088   if (Thread::is_interrupted (THREAD, true) && !HAS_PENDING_EXCEPTION) {
3089     THROW_MSG(vmSymbols::java_lang_InterruptedException(), "sleep interrupted");
3090   }
3091 
3092   // Save current thread state and restore it at the end of this block.
3093   // And set new thread state to SLEEPING.
3094   JavaThreadSleepState jtss(thread);
3095 
3096   HOTSPOT_THREAD_SLEEP_BEGIN(millis);
3097 
3098   EventThreadSleep event;
3099 
3100   if (millis == 0) {
3101     // When ConvertSleepToYield is on, this matches the classic VM implementation of
3102     // JVM_Sleep. Critical for similar threading behaviour (Win32)
3103     // It appears that in certain GUI contexts, it may be beneficial to do a short sleep
3104     // for SOLARIS
3105     if (ConvertSleepToYield) {
3106       os::naked_yield();
3107     } else {
3108       ThreadState old_state = thread->osthread()->get_state();
3109       thread->osthread()->set_state(SLEEPING);
3110       os::sleep(thread, MinSleepInterval, false);
3111       thread->osthread()->set_state(old_state);
3112     }
3113   } else {
3114     ThreadState old_state = thread->osthread()->get_state();
3115     thread->osthread()->set_state(SLEEPING);
3116     if (os::sleep(thread, millis, true) == OS_INTRPT) {
3117       // An asynchronous exception (e.g., ThreadDeathException) could have been thrown on
3118       // us while we were sleeping. We do not overwrite those.
3119       if (!HAS_PENDING_EXCEPTION) {
3120         if (event.should_commit()) {
3121           event.set_time(millis);
3122           event.commit();
3123         }
3124         HOTSPOT_THREAD_SLEEP_END(1);
3125 
3126         // TODO-FIXME: THROW_MSG returns which means we will not call set_state()
3127         // to properly restore the thread state.  That's likely wrong.
3128         THROW_MSG(vmSymbols::java_lang_InterruptedException(), "sleep interrupted");
3129       }
3130     }
3131     thread->osthread()->set_state(old_state);
3132   }
3133   if (event.should_commit()) {
3134     event.set_time(millis);
3135     event.commit();
3136   }
3137   HOTSPOT_THREAD_SLEEP_END(0);
3138 JVM_END
3139 
3140 JVM_ENTRY(jobject, JVM_CurrentThread(JNIEnv* env, jclass threadClass))
3141   JVMWrapper("JVM_CurrentThread");
3142   oop jthread = thread->threadObj();
3143   assert (thread != NULL, "no current thread!");
3144   return JNIHandles::make_local(env, jthread);
3145 JVM_END
3146 
3147 
3148 JVM_ENTRY(jint, JVM_CountStackFrames(JNIEnv* env, jobject jthread))
3149   JVMWrapper("JVM_CountStackFrames");
3150 
3151   // Ensure that the C++ Thread and OSThread structures aren't freed before we operate
3152   oop java_thread = JNIHandles::resolve_non_null(jthread);
3153   bool throw_illegal_thread_state = false;
3154   int count = 0;
3155 
3156   {
3157     MutexLockerEx ml(thread->threadObj() == java_thread ? NULL : Threads_lock);
3158     // We need to re-resolve the java_thread, since a GC might have happened during the
3159     // acquire of the lock
3160     JavaThread* thr = java_lang_Thread::thread(JNIHandles::resolve_non_null(jthread));
3161 
3162     if (thr == NULL) {
3163       // do nothing
3164     } else if(! thr->is_external_suspend() || ! thr->frame_anchor()->walkable()) {
3165       // Check whether this java thread has been suspended already. If not, throws
3166       // IllegalThreadStateException. We defer to throw that exception until
3167       // Threads_lock is released since loading exception class has to leave VM.
3168       // The correct way to test a thread is actually suspended is
3169       // wait_for_ext_suspend_completion(), but we can't call that while holding
3170       // the Threads_lock. The above tests are sufficient for our purposes
3171       // provided the walkability of the stack is stable - which it isn't
3172       // 100% but close enough for most practical purposes.
3173       throw_illegal_thread_state = true;
3174     } else {
3175       // Count all java activation, i.e., number of vframes
3176       for(vframeStream vfst(thr); !vfst.at_end(); vfst.next()) {
3177         // Native frames are not counted
3178         if (!vfst.method()->is_native()) count++;
3179        }
3180     }
3181   }
3182 
3183   if (throw_illegal_thread_state) {
3184     THROW_MSG_0(vmSymbols::java_lang_IllegalThreadStateException(),
3185                 "this thread is not suspended");
3186   }
3187   return count;
3188 JVM_END
3189 
3190 // Consider: A better way to implement JVM_Interrupt() is to acquire
3191 // Threads_lock to resolve the jthread into a Thread pointer, fetch
3192 // Thread->platformevent, Thread->native_thr, Thread->parker, etc.,
3193 // drop Threads_lock, and the perform the unpark() and thr_kill() operations
3194 // outside the critical section.  Threads_lock is hot so we want to minimize
3195 // the hold-time.  A cleaner interface would be to decompose interrupt into
3196 // two steps.  The 1st phase, performed under Threads_lock, would return
3197 // a closure that'd be invoked after Threads_lock was dropped.
3198 // This tactic is safe as PlatformEvent and Parkers are type-stable (TSM) and
3199 // admit spurious wakeups.
3200 
3201 JVM_ENTRY(void, JVM_Interrupt(JNIEnv* env, jobject jthread))
3202   JVMWrapper("JVM_Interrupt");
3203 
3204   // Ensure that the C++ Thread and OSThread structures aren't freed before we operate
3205   oop java_thread = JNIHandles::resolve_non_null(jthread);
3206   MutexLockerEx ml(thread->threadObj() == java_thread ? NULL : Threads_lock);
3207   // We need to re-resolve the java_thread, since a GC might have happened during the
3208   // acquire of the lock
3209   JavaThread* thr = java_lang_Thread::thread(JNIHandles::resolve_non_null(jthread));
3210   if (thr != NULL) {
3211     Thread::interrupt(thr);
3212   }
3213 JVM_END
3214 
3215 
3216 JVM_QUICK_ENTRY(jboolean, JVM_IsInterrupted(JNIEnv* env, jobject jthread, jboolean clear_interrupted))
3217   JVMWrapper("JVM_IsInterrupted");
3218 
3219   // Ensure that the C++ Thread and OSThread structures aren't freed before we operate
3220   oop java_thread = JNIHandles::resolve_non_null(jthread);
3221   MutexLockerEx ml(thread->threadObj() == java_thread ? NULL : Threads_lock);
3222   // We need to re-resolve the java_thread, since a GC might have happened during the
3223   // acquire of the lock
3224   JavaThread* thr = java_lang_Thread::thread(JNIHandles::resolve_non_null(jthread));
3225   if (thr == NULL) {
3226     return JNI_FALSE;
3227   } else {
3228     return (jboolean) Thread::is_interrupted(thr, clear_interrupted != 0);
3229   }
3230 JVM_END
3231 
3232 
3233 // Return true iff the current thread has locked the object passed in
3234 
3235 JVM_ENTRY(jboolean, JVM_HoldsLock(JNIEnv* env, jclass threadClass, jobject obj))
3236   JVMWrapper("JVM_HoldsLock");
3237   assert(THREAD->is_Java_thread(), "sanity check");
3238   if (obj == NULL) {
3239     THROW_(vmSymbols::java_lang_NullPointerException(), JNI_FALSE);
3240   }
3241   Handle h_obj(THREAD, JNIHandles::resolve(obj));
3242   return ObjectSynchronizer::current_thread_holds_lock((JavaThread*)THREAD, h_obj);
3243 JVM_END
3244 
3245 
3246 JVM_ENTRY(void, JVM_DumpAllStacks(JNIEnv* env, jclass))
3247   JVMWrapper("JVM_DumpAllStacks");
3248   VM_PrintThreads op;
3249   VMThread::execute(&op);
3250   if (JvmtiExport::should_post_data_dump()) {
3251     JvmtiExport::post_data_dump();
3252   }
3253 JVM_END
3254 
3255 JVM_ENTRY(void, JVM_SetNativeThreadName(JNIEnv* env, jobject jthread, jstring name))
3256   JVMWrapper("JVM_SetNativeThreadName");
3257   ResourceMark rm(THREAD);
3258   oop java_thread = JNIHandles::resolve_non_null(jthread);
3259   JavaThread* thr = java_lang_Thread::thread(java_thread);
3260   // Thread naming only supported for the current thread, doesn't work for
3261   // target threads.
3262   if (Thread::current() == thr && !thr->has_attached_via_jni()) {
3263     // we don't set the name of an attached thread to avoid stepping
3264     // on other programs
3265     const char *thread_name = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(name));
3266     os::set_native_thread_name(thread_name);
3267   }
3268 JVM_END
3269 
3270 // java.lang.SecurityManager ///////////////////////////////////////////////////////////////////////
3271 
3272 static bool is_trusted_frame(JavaThread* jthread, vframeStream* vfst) {
3273   assert(jthread->is_Java_thread(), "must be a Java thread");
3274   if (jthread->privileged_stack_top() == NULL) return false;
3275   if (jthread->privileged_stack_top()->frame_id() == vfst->frame_id()) {
3276     oop loader = jthread->privileged_stack_top()->class_loader();
3277     if (loader == NULL) return true;
3278     bool trusted = java_lang_ClassLoader::is_trusted_loader(loader);
3279     if (trusted) return true;
3280   }
3281   return false;
3282 }
3283 
3284 JVM_ENTRY(jclass, JVM_CurrentLoadedClass(JNIEnv *env))
3285   JVMWrapper("JVM_CurrentLoadedClass");
3286   ResourceMark rm(THREAD);
3287 
3288   for (vframeStream vfst(thread); !vfst.at_end(); vfst.next()) {
3289     // if a method in a class in a trusted loader is in a doPrivileged, return NULL
3290     bool trusted = is_trusted_frame(thread, &vfst);
3291     if (trusted) return NULL;
3292 
3293     Method* m = vfst.method();
3294     if (!m->is_native()) {
3295       InstanceKlass* holder = m->method_holder();
3296       oop loader = holder->class_loader();
3297       if (loader != NULL && !java_lang_ClassLoader::is_trusted_loader(loader)) {
3298         return (jclass) JNIHandles::make_local(env, holder->java_mirror());
3299       }
3300     }
3301   }
3302   return NULL;
3303 JVM_END
3304 
3305 
3306 JVM_ENTRY(jobject, JVM_CurrentClassLoader(JNIEnv *env))
3307   JVMWrapper("JVM_CurrentClassLoader");
3308   ResourceMark rm(THREAD);
3309 
3310   for (vframeStream vfst(thread); !vfst.at_end(); vfst.next()) {
3311 
3312     // if a method in a class in a trusted loader is in a doPrivileged, return NULL
3313     bool trusted = is_trusted_frame(thread, &vfst);
3314     if (trusted) return NULL;
3315 
3316     Method* m = vfst.method();
3317     if (!m->is_native()) {
3318       InstanceKlass* holder = m->method_holder();
3319       assert(holder->is_klass(), "just checking");
3320       oop loader = holder->class_loader();
3321       if (loader != NULL && !java_lang_ClassLoader::is_trusted_loader(loader)) {
3322         return JNIHandles::make_local(env, loader);
3323       }
3324     }
3325   }
3326   return NULL;
3327 JVM_END
3328 
3329 
3330 JVM_ENTRY(jobjectArray, JVM_GetClassContext(JNIEnv *env))
3331   JVMWrapper("JVM_GetClassContext");
3332   ResourceMark rm(THREAD);
3333   JvmtiVMObjectAllocEventCollector oam;
3334   vframeStream vfst(thread);
3335 
3336   if (SystemDictionary::reflect_CallerSensitive_klass() != NULL) {
3337     // This must only be called from SecurityManager.getClassContext
3338     Method* m = vfst.method();
3339     if (!(m->method_holder() == SystemDictionary::SecurityManager_klass() &&
3340           m->name()          == vmSymbols::getClassContext_name() &&
3341           m->signature()     == vmSymbols::void_class_array_signature())) {
3342       THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), "JVM_GetClassContext must only be called from SecurityManager.getClassContext");
3343     }
3344   }
3345 
3346   // Collect method holders
3347   GrowableArray<KlassHandle>* klass_array = new GrowableArray<KlassHandle>();
3348   for (; !vfst.at_end(); vfst.security_next()) {
3349     Method* m = vfst.method();
3350     // Native frames are not returned
3351     if (!m->is_ignored_by_security_stack_walk() && !m->is_native()) {
3352       Klass* holder = m->method_holder();
3353       assert(holder->is_klass(), "just checking");
3354       klass_array->append(holder);
3355     }
3356   }
3357 
3358   // Create result array of type [Ljava/lang/Class;
3359   objArrayOop result = oopFactory::new_objArray(SystemDictionary::Class_klass(), klass_array->length(), CHECK_NULL);
3360   // Fill in mirrors corresponding to method holders
3361   for (int i = 0; i < klass_array->length(); i++) {
3362     result->obj_at_put(i, klass_array->at(i)->java_mirror());
3363   }
3364 
3365   return (jobjectArray) JNIHandles::make_local(env, result);
3366 JVM_END
3367 
3368 
3369 JVM_ENTRY(jint, JVM_ClassDepth(JNIEnv *env, jstring name))
3370   JVMWrapper("JVM_ClassDepth");
3371   ResourceMark rm(THREAD);
3372   Handle h_name (THREAD, JNIHandles::resolve_non_null(name));
3373   Handle class_name_str = java_lang_String::internalize_classname(h_name, CHECK_0);
3374 
3375   const char* str = java_lang_String::as_utf8_string(class_name_str());
3376   TempNewSymbol class_name_sym = SymbolTable::probe(str, (int)strlen(str));
3377   if (class_name_sym == NULL) {
3378     return -1;
3379   }
3380 
3381   int depth = 0;
3382 
3383   for(vframeStream vfst(thread); !vfst.at_end(); vfst.next()) {
3384     if (!vfst.method()->is_native()) {
3385       InstanceKlass* holder = vfst.method()->method_holder();
3386       assert(holder->is_klass(), "just checking");
3387       if (holder->name() == class_name_sym) {
3388         return depth;
3389       }
3390       depth++;
3391     }
3392   }
3393   return -1;
3394 JVM_END
3395 
3396 
3397 JVM_ENTRY(jint, JVM_ClassLoaderDepth(JNIEnv *env))
3398   JVMWrapper("JVM_ClassLoaderDepth");
3399   ResourceMark rm(THREAD);
3400   int depth = 0;
3401   for (vframeStream vfst(thread); !vfst.at_end(); vfst.next()) {
3402     // if a method in a class in a trusted loader is in a doPrivileged, return -1
3403     bool trusted = is_trusted_frame(thread, &vfst);
3404     if (trusted) return -1;
3405 
3406     Method* m = vfst.method();
3407     if (!m->is_native()) {
3408       InstanceKlass* holder = m->method_holder();
3409       assert(holder->is_klass(), "just checking");
3410       oop loader = holder->class_loader();
3411       if (loader != NULL && !java_lang_ClassLoader::is_trusted_loader(loader)) {
3412         return depth;
3413       }
3414       depth++;
3415     }
3416   }
3417   return -1;
3418 JVM_END
3419 
3420 
3421 // java.lang.Package ////////////////////////////////////////////////////////////////
3422 
3423 
3424 JVM_ENTRY(jstring, JVM_GetSystemPackage(JNIEnv *env, jstring name))
3425   JVMWrapper("JVM_GetSystemPackage");
3426   ResourceMark rm(THREAD);
3427   JvmtiVMObjectAllocEventCollector oam;
3428   char* str = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(name));
3429   oop result = ClassLoader::get_system_package(str, CHECK_NULL);
3430   return (jstring) JNIHandles::make_local(result);
3431 JVM_END
3432 
3433 
3434 JVM_ENTRY(jobjectArray, JVM_GetSystemPackages(JNIEnv *env))
3435   JVMWrapper("JVM_GetSystemPackages");
3436   JvmtiVMObjectAllocEventCollector oam;
3437   objArrayOop result = ClassLoader::get_system_packages(CHECK_NULL);
3438   return (jobjectArray) JNIHandles::make_local(result);
3439 JVM_END
3440 
3441 
3442 // ObjectInputStream ///////////////////////////////////////////////////////////////
3443 
3444 bool force_verify_field_access(Klass* current_class, Klass* field_class, AccessFlags access, bool classloader_only) {
3445   if (current_class == NULL) {
3446     return true;
3447   }
3448   if ((current_class == field_class) || access.is_public()) {
3449     return true;
3450   }
3451 
3452   if (access.is_protected()) {
3453     // See if current_class is a subclass of field_class
3454     if (current_class->is_subclass_of(field_class)) {
3455       return true;
3456     }
3457   }
3458 
3459   return (!access.is_private() && InstanceKlass::cast(current_class)->is_same_class_package(field_class));
3460 }
3461 
3462 
3463 // JVM_AllocateNewObject and JVM_AllocateNewArray are unused as of 1.4
3464 JVM_ENTRY(jobject, JVM_AllocateNewObject(JNIEnv *env, jobject receiver, jclass currClass, jclass initClass))
3465   JVMWrapper("JVM_AllocateNewObject");
3466   JvmtiVMObjectAllocEventCollector oam;
3467   // Receiver is not used
3468   oop curr_mirror = JNIHandles::resolve_non_null(currClass);
3469   oop init_mirror = JNIHandles::resolve_non_null(initClass);
3470 
3471   // Cannot instantiate primitive types
3472   if (java_lang_Class::is_primitive(curr_mirror) || java_lang_Class::is_primitive(init_mirror)) {
3473     ResourceMark rm(THREAD);
3474     THROW_0(vmSymbols::java_lang_InvalidClassException());
3475   }
3476 
3477   // Arrays not allowed here, must use JVM_AllocateNewArray
3478   if (java_lang_Class::as_Klass(curr_mirror)->oop_is_array() ||
3479       java_lang_Class::as_Klass(init_mirror)->oop_is_array()) {
3480     ResourceMark rm(THREAD);
3481     THROW_0(vmSymbols::java_lang_InvalidClassException());
3482   }
3483 
3484   instanceKlassHandle curr_klass (THREAD, java_lang_Class::as_Klass(curr_mirror));
3485   instanceKlassHandle init_klass (THREAD, java_lang_Class::as_Klass(init_mirror));
3486 
3487   assert(curr_klass->is_subclass_of(init_klass()), "just checking");
3488 
3489   // Interfaces, abstract classes, and java.lang.Class classes cannot be instantiated directly.
3490   curr_klass->check_valid_for_instantiation(false, CHECK_NULL);
3491 
3492   // Make sure klass is initialized, since we are about to instantiate one of them.
3493   curr_klass->initialize(CHECK_NULL);
3494 
3495  methodHandle m (THREAD,
3496                  init_klass->find_method(vmSymbols::object_initializer_name(),
3497                                          vmSymbols::void_method_signature()));
3498   if (m.is_null()) {
3499     ResourceMark rm(THREAD);
3500     THROW_MSG_0(vmSymbols::java_lang_NoSuchMethodError(),
3501                 Method::name_and_sig_as_C_string(init_klass(),
3502                                           vmSymbols::object_initializer_name(),
3503                                           vmSymbols::void_method_signature()));
3504   }
3505 
3506   if (curr_klass ==  init_klass && !m->is_public()) {
3507     // Calling the constructor for class 'curr_klass'.
3508     // Only allow calls to a public no-arg constructor.
3509     // This path corresponds to creating an Externalizable object.
3510     THROW_0(vmSymbols::java_lang_IllegalAccessException());
3511   }
3512 
3513   if (!force_verify_field_access(curr_klass(), init_klass(), m->access_flags(), false)) {
3514     // subclass 'curr_klass' does not have access to no-arg constructor of 'initcb'
3515     THROW_0(vmSymbols::java_lang_IllegalAccessException());
3516   }
3517 
3518   Handle obj = curr_klass->allocate_instance_handle(CHECK_NULL);
3519   // Call constructor m. This might call a constructor higher up in the hierachy
3520   JavaCalls::call_default_constructor(thread, m, obj, CHECK_NULL);
3521 
3522   return JNIHandles::make_local(obj());
3523 JVM_END
3524 
3525 
3526 JVM_ENTRY(jobject, JVM_AllocateNewArray(JNIEnv *env, jobject obj, jclass currClass, jint length))
3527   JVMWrapper("JVM_AllocateNewArray");
3528   JvmtiVMObjectAllocEventCollector oam;
3529   oop mirror = JNIHandles::resolve_non_null(currClass);
3530 
3531   if (java_lang_Class::is_primitive(mirror)) {
3532     THROW_0(vmSymbols::java_lang_InvalidClassException());
3533   }
3534   Klass* k = java_lang_Class::as_Klass(mirror);
3535   oop result;
3536 
3537   if (k->oop_is_typeArray()) {
3538     // typeArray
3539     result = TypeArrayKlass::cast(k)->allocate(length, CHECK_NULL);
3540   } else if (k->oop_is_objArray()) {
3541     // objArray
3542     ObjArrayKlass* oak = ObjArrayKlass::cast(k);
3543     oak->initialize(CHECK_NULL); // make sure class is initialized (matches Classic VM behavior)
3544     result = oak->allocate(length, CHECK_NULL);
3545   } else {
3546     THROW_0(vmSymbols::java_lang_InvalidClassException());
3547   }
3548   return JNIHandles::make_local(env, result);
3549 JVM_END
3550 
3551 
3552 // Return the first non-null class loader up the execution stack, or null
3553 // if only code from the null class loader is on the stack.
3554 
3555 JVM_ENTRY(jobject, JVM_LatestUserDefinedLoader(JNIEnv *env))
3556   for (vframeStream vfst(thread); !vfst.at_end(); vfst.next()) {
3557     vfst.skip_reflection_related_frames(); // Only needed for 1.4 reflection
3558     oop loader = vfst.method()->method_holder()->class_loader();
3559     if (loader != NULL) {
3560       return JNIHandles::make_local(env, loader);
3561     }
3562   }
3563   return NULL;
3564 JVM_END
3565 
3566 
3567 // Load a class relative to the most recent class on the stack  with a non-null
3568 // classloader.
3569 // This function has been deprecated and should not be considered part of the
3570 // specified JVM interface.
3571 
3572 JVM_ENTRY(jclass, JVM_LoadClass0(JNIEnv *env, jobject receiver,
3573                                  jclass currClass, jstring currClassName))
3574   JVMWrapper("JVM_LoadClass0");
3575   // Receiver is not used
3576   ResourceMark rm(THREAD);
3577 
3578   // Class name argument is not guaranteed to be in internal format
3579   Handle classname (THREAD, JNIHandles::resolve_non_null(currClassName));
3580   Handle string = java_lang_String::internalize_classname(classname, CHECK_NULL);
3581 
3582   const char* str = java_lang_String::as_utf8_string(string());
3583 
3584   if (str == NULL || (int)strlen(str) > Symbol::max_length()) {
3585     // It's impossible to create this class;  the name cannot fit
3586     // into the constant pool.
3587     THROW_MSG_0(vmSymbols::java_lang_NoClassDefFoundError(), str);
3588   }
3589 
3590   TempNewSymbol name = SymbolTable::new_symbol(str, CHECK_NULL);
3591   Handle curr_klass (THREAD, JNIHandles::resolve(currClass));
3592   // Find the most recent class on the stack with a non-null classloader
3593   oop loader = NULL;
3594   oop protection_domain = NULL;
3595   if (curr_klass.is_null()) {
3596     for (vframeStream vfst(thread);
3597          !vfst.at_end() && loader == NULL;
3598          vfst.next()) {
3599       if (!vfst.method()->is_native()) {
3600         InstanceKlass* holder = vfst.method()->method_holder();
3601         loader             = holder->class_loader();
3602         protection_domain  = holder->protection_domain();
3603       }
3604     }
3605   } else {
3606     Klass* curr_klass_oop = java_lang_Class::as_Klass(curr_klass());
3607     loader            = InstanceKlass::cast(curr_klass_oop)->class_loader();
3608     protection_domain = InstanceKlass::cast(curr_klass_oop)->protection_domain();
3609   }
3610   Handle h_loader(THREAD, loader);
3611   Handle h_prot  (THREAD, protection_domain);
3612   jclass result =  find_class_from_class_loader(env, name, true, h_loader, h_prot,
3613                                                 false, thread);
3614   if (TraceClassResolution && result != NULL) {
3615     trace_class_resolution(java_lang_Class::as_Klass(JNIHandles::resolve_non_null(result)));
3616   }
3617   return result;
3618 JVM_END
3619 
3620 
3621 // Array ///////////////////////////////////////////////////////////////////////////////////////////
3622 
3623 
3624 // resolve array handle and check arguments
3625 static inline arrayOop check_array(JNIEnv *env, jobject arr, bool type_array_only, TRAPS) {
3626   if (arr == NULL) {
3627     THROW_0(vmSymbols::java_lang_NullPointerException());
3628   }
3629   oop a = JNIHandles::resolve_non_null(arr);
3630   if (!a->is_array() || (type_array_only && !a->is_typeArray())) {
3631     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Argument is not an array");
3632   }
3633   return arrayOop(a);
3634 }
3635 
3636 
3637 JVM_ENTRY(jint, JVM_GetArrayLength(JNIEnv *env, jobject arr))
3638   JVMWrapper("JVM_GetArrayLength");
3639   arrayOop a = check_array(env, arr, false, CHECK_0);
3640   return a->length();
3641 JVM_END
3642 
3643 
3644 JVM_ENTRY(jobject, JVM_GetArrayElement(JNIEnv *env, jobject arr, jint index))
3645   JVMWrapper("JVM_Array_Get");
3646   JvmtiVMObjectAllocEventCollector oam;
3647   arrayOop a = check_array(env, arr, false, CHECK_NULL);
3648   jvalue value;
3649   BasicType type = Reflection::array_get(&value, a, index, CHECK_NULL);
3650   oop box = Reflection::box(&value, type, CHECK_NULL);
3651   return JNIHandles::make_local(env, box);
3652 JVM_END
3653 
3654 
3655 JVM_ENTRY(jvalue, JVM_GetPrimitiveArrayElement(JNIEnv *env, jobject arr, jint index, jint wCode))
3656   JVMWrapper("JVM_GetPrimitiveArrayElement");
3657   jvalue value;
3658   value.i = 0; // to initialize value before getting used in CHECK
3659   arrayOop a = check_array(env, arr, true, CHECK_(value));
3660   assert(a->is_typeArray(), "just checking");
3661   BasicType type = Reflection::array_get(&value, a, index, CHECK_(value));
3662   BasicType wide_type = (BasicType) wCode;
3663   if (type != wide_type) {
3664     Reflection::widen(&value, type, wide_type, CHECK_(value));
3665   }
3666   return value;
3667 JVM_END
3668 
3669 
3670 JVM_ENTRY(void, JVM_SetArrayElement(JNIEnv *env, jobject arr, jint index, jobject val))
3671   JVMWrapper("JVM_SetArrayElement");
3672   arrayOop a = check_array(env, arr, false, CHECK);
3673   oop box = JNIHandles::resolve(val);
3674   jvalue value;
3675   value.i = 0; // to initialize value before getting used in CHECK
3676   BasicType value_type;
3677   if (a->is_objArray()) {
3678     // Make sure we do no unbox e.g. java/lang/Integer instances when storing into an object array
3679     value_type = Reflection::unbox_for_regular_object(box, &value);
3680   } else {
3681     value_type = Reflection::unbox_for_primitive(box, &value, CHECK);
3682   }
3683   Reflection::array_set(&value, a, index, value_type, CHECK);
3684 JVM_END
3685 
3686 
3687 JVM_ENTRY(void, JVM_SetPrimitiveArrayElement(JNIEnv *env, jobject arr, jint index, jvalue v, unsigned char vCode))
3688   JVMWrapper("JVM_SetPrimitiveArrayElement");
3689   arrayOop a = check_array(env, arr, true, CHECK);
3690   assert(a->is_typeArray(), "just checking");
3691   BasicType value_type = (BasicType) vCode;
3692   Reflection::array_set(&v, a, index, value_type, CHECK);
3693 JVM_END
3694 
3695 
3696 JVM_ENTRY(jobject, JVM_NewArray(JNIEnv *env, jclass eltClass, jint length))
3697   JVMWrapper("JVM_NewArray");
3698   JvmtiVMObjectAllocEventCollector oam;
3699   oop element_mirror = JNIHandles::resolve(eltClass);
3700   oop result = Reflection::reflect_new_array(element_mirror, length, CHECK_NULL);
3701   return JNIHandles::make_local(env, result);
3702 JVM_END
3703 
3704 
3705 JVM_ENTRY(jobject, JVM_NewMultiArray(JNIEnv *env, jclass eltClass, jintArray dim))
3706   JVMWrapper("JVM_NewMultiArray");
3707   JvmtiVMObjectAllocEventCollector oam;
3708   arrayOop dim_array = check_array(env, dim, true, CHECK_NULL);
3709   oop element_mirror = JNIHandles::resolve(eltClass);
3710   assert(dim_array->is_typeArray(), "just checking");
3711   oop result = Reflection::reflect_new_multi_array(element_mirror, typeArrayOop(dim_array), CHECK_NULL);
3712   return JNIHandles::make_local(env, result);
3713 JVM_END
3714 
3715 
3716 // Networking library support ////////////////////////////////////////////////////////////////////
3717 
3718 JVM_LEAF(jint, JVM_InitializeSocketLibrary())
3719   JVMWrapper("JVM_InitializeSocketLibrary");
3720   return 0;
3721 JVM_END
3722 
3723 
3724 JVM_LEAF(jint, JVM_Socket(jint domain, jint type, jint protocol))
3725   JVMWrapper("JVM_Socket");
3726   return os::socket(domain, type, protocol);
3727 JVM_END
3728 
3729 
3730 JVM_LEAF(jint, JVM_SocketClose(jint fd))
3731   JVMWrapper2("JVM_SocketClose (0x%x)", fd);
3732   //%note jvm_r6
3733   return os::socket_close(fd);
3734 JVM_END
3735 
3736 
3737 JVM_LEAF(jint, JVM_SocketShutdown(jint fd, jint howto))
3738   JVMWrapper2("JVM_SocketShutdown (0x%x)", fd);
3739   //%note jvm_r6
3740   return os::socket_shutdown(fd, howto);
3741 JVM_END
3742 
3743 
3744 JVM_LEAF(jint, JVM_Recv(jint fd, char *buf, jint nBytes, jint flags))
3745   JVMWrapper2("JVM_Recv (0x%x)", fd);
3746   //%note jvm_r6
3747   return os::recv(fd, buf, (size_t)nBytes, (uint)flags);
3748 JVM_END
3749 
3750 
3751 JVM_LEAF(jint, JVM_Send(jint fd, char *buf, jint nBytes, jint flags))
3752   JVMWrapper2("JVM_Send (0x%x)", fd);
3753   //%note jvm_r6
3754   return os::send(fd, buf, (size_t)nBytes, (uint)flags);
3755 JVM_END
3756 
3757 
3758 JVM_LEAF(jint, JVM_Timeout(int fd, long timeout))
3759   JVMWrapper2("JVM_Timeout (0x%x)", fd);
3760   //%note jvm_r6
3761   return os::timeout(fd, timeout);
3762 JVM_END
3763 
3764 
3765 JVM_LEAF(jint, JVM_Listen(jint fd, jint count))
3766   JVMWrapper2("JVM_Listen (0x%x)", fd);
3767   //%note jvm_r6
3768   return os::listen(fd, count);
3769 JVM_END
3770 
3771 
3772 JVM_LEAF(jint, JVM_Connect(jint fd, struct sockaddr *him, jint len))
3773   JVMWrapper2("JVM_Connect (0x%x)", fd);
3774   //%note jvm_r6
3775   return os::connect(fd, him, (socklen_t)len);
3776 JVM_END
3777 
3778 
3779 JVM_LEAF(jint, JVM_Bind(jint fd, struct sockaddr *him, jint len))
3780   JVMWrapper2("JVM_Bind (0x%x)", fd);
3781   //%note jvm_r6
3782   return os::bind(fd, him, (socklen_t)len);
3783 JVM_END
3784 
3785 
3786 JVM_LEAF(jint, JVM_Accept(jint fd, struct sockaddr *him, jint *len))
3787   JVMWrapper2("JVM_Accept (0x%x)", fd);
3788   //%note jvm_r6
3789   socklen_t socklen = (socklen_t)(*len);
3790   jint result = os::accept(fd, him, &socklen);
3791   *len = (jint)socklen;
3792   return result;
3793 JVM_END
3794 
3795 
3796 JVM_LEAF(jint, JVM_RecvFrom(jint fd, char *buf, int nBytes, int flags, struct sockaddr *from, int *fromlen))
3797   JVMWrapper2("JVM_RecvFrom (0x%x)", fd);
3798   //%note jvm_r6
3799   socklen_t socklen = (socklen_t)(*fromlen);
3800   jint result = os::recvfrom(fd, buf, (size_t)nBytes, (uint)flags, from, &socklen);
3801   *fromlen = (int)socklen;
3802   return result;
3803 JVM_END
3804 
3805 
3806 JVM_LEAF(jint, JVM_GetSockName(jint fd, struct sockaddr *him, int *len))
3807   JVMWrapper2("JVM_GetSockName (0x%x)", fd);
3808   //%note jvm_r6
3809   socklen_t socklen = (socklen_t)(*len);
3810   jint result = os::get_sock_name(fd, him, &socklen);
3811   *len = (int)socklen;
3812   return result;
3813 JVM_END
3814 
3815 
3816 JVM_LEAF(jint, JVM_SendTo(jint fd, char *buf, int len, int flags, struct sockaddr *to, int tolen))
3817   JVMWrapper2("JVM_SendTo (0x%x)", fd);
3818   //%note jvm_r6
3819   return os::sendto(fd, buf, (size_t)len, (uint)flags, to, (socklen_t)tolen);
3820 JVM_END
3821 
3822 
3823 JVM_LEAF(jint, JVM_SocketAvailable(jint fd, jint *pbytes))
3824   JVMWrapper2("JVM_SocketAvailable (0x%x)", fd);
3825   //%note jvm_r6
3826   return os::socket_available(fd, pbytes);
3827 JVM_END
3828 
3829 
3830 JVM_LEAF(jint, JVM_GetSockOpt(jint fd, int level, int optname, char *optval, int *optlen))
3831   JVMWrapper2("JVM_GetSockOpt (0x%x)", fd);
3832   //%note jvm_r6
3833   socklen_t socklen = (socklen_t)(*optlen);
3834   jint result = os::get_sock_opt(fd, level, optname, optval, &socklen);
3835   *optlen = (int)socklen;
3836   return result;
3837 JVM_END
3838 
3839 
3840 JVM_LEAF(jint, JVM_SetSockOpt(jint fd, int level, int optname, const char *optval, int optlen))
3841   JVMWrapper2("JVM_GetSockOpt (0x%x)", fd);
3842   //%note jvm_r6
3843   return os::set_sock_opt(fd, level, optname, optval, (socklen_t)optlen);
3844 JVM_END
3845 
3846 
3847 JVM_LEAF(int, JVM_GetHostName(char* name, int namelen))
3848   JVMWrapper("JVM_GetHostName");
3849   return os::get_host_name(name, namelen);
3850 JVM_END
3851 
3852 
3853 // Library support ///////////////////////////////////////////////////////////////////////////
3854 
3855 JVM_ENTRY_NO_ENV(void*, JVM_LoadLibrary(const char* name))
3856   //%note jvm_ct
3857   JVMWrapper2("JVM_LoadLibrary (%s)", name);
3858   char ebuf[1024];
3859   void *load_result;
3860   {
3861     ThreadToNativeFromVM ttnfvm(thread);
3862     load_result = os::dll_load(name, ebuf, sizeof ebuf);
3863   }
3864   if (load_result == NULL) {
3865     char msg[1024];
3866     jio_snprintf(msg, sizeof msg, "%s: %s", name, ebuf);
3867     // Since 'ebuf' may contain a string encoded using
3868     // platform encoding scheme, we need to pass
3869     // Exceptions::unsafe_to_utf8 to the new_exception method
3870     // as the last argument. See bug 6367357.
3871     Handle h_exception =
3872       Exceptions::new_exception(thread,
3873                                 vmSymbols::java_lang_UnsatisfiedLinkError(),
3874                                 msg, Exceptions::unsafe_to_utf8);
3875 
3876     THROW_HANDLE_0(h_exception);
3877   }
3878   return load_result;
3879 JVM_END
3880 
3881 
3882 JVM_LEAF(void, JVM_UnloadLibrary(void* handle))
3883   JVMWrapper("JVM_UnloadLibrary");
3884   os::dll_unload(handle);
3885 JVM_END
3886 
3887 
3888 JVM_LEAF(void*, JVM_FindLibraryEntry(void* handle, const char* name))
3889   JVMWrapper2("JVM_FindLibraryEntry (%s)", name);
3890   return os::dll_lookup(handle, name);
3891 JVM_END
3892 
3893 
3894 // Floating point support ////////////////////////////////////////////////////////////////////
3895 
3896 JVM_LEAF(jboolean, JVM_IsNaN(jdouble a))
3897   JVMWrapper("JVM_IsNaN");
3898   return g_isnan(a);
3899 JVM_END
3900 
3901 
3902 // JNI version ///////////////////////////////////////////////////////////////////////////////
3903 
3904 JVM_LEAF(jboolean, JVM_IsSupportedJNIVersion(jint version))
3905   JVMWrapper2("JVM_IsSupportedJNIVersion (%d)", version);
3906   return Threads::is_supported_jni_version_including_1_1(version);
3907 JVM_END
3908 
3909 
3910 // String support ///////////////////////////////////////////////////////////////////////////
3911 
3912 JVM_ENTRY(jstring, JVM_InternString(JNIEnv *env, jstring str))
3913   JVMWrapper("JVM_InternString");
3914   JvmtiVMObjectAllocEventCollector oam;
3915   if (str == NULL) return NULL;
3916   oop string = JNIHandles::resolve_non_null(str);
3917   oop result = StringTable::intern(string, CHECK_NULL);
3918   return (jstring) JNIHandles::make_local(env, result);
3919 JVM_END
3920 
3921 
3922 // Raw monitor support //////////////////////////////////////////////////////////////////////
3923 
3924 // The lock routine below calls lock_without_safepoint_check in order to get a raw lock
3925 // without interfering with the safepoint mechanism. The routines are not JVM_LEAF because
3926 // they might be called by non-java threads. The JVM_LEAF installs a NoHandleMark check
3927 // that only works with java threads.
3928 
3929 
3930 JNIEXPORT void* JNICALL JVM_RawMonitorCreate(void) {
3931   VM_Exit::block_if_vm_exited();
3932   JVMWrapper("JVM_RawMonitorCreate");
3933   return new Mutex(Mutex::native, "JVM_RawMonitorCreate");
3934 }
3935 
3936 
3937 JNIEXPORT void JNICALL  JVM_RawMonitorDestroy(void *mon) {
3938   VM_Exit::block_if_vm_exited();
3939   JVMWrapper("JVM_RawMonitorDestroy");
3940   delete ((Mutex*) mon);
3941 }
3942 
3943 
3944 JNIEXPORT jint JNICALL JVM_RawMonitorEnter(void *mon) {
3945   VM_Exit::block_if_vm_exited();
3946   JVMWrapper("JVM_RawMonitorEnter");
3947   ((Mutex*) mon)->jvm_raw_lock();
3948   return 0;
3949 }
3950 
3951 
3952 JNIEXPORT void JNICALL JVM_RawMonitorExit(void *mon) {
3953   VM_Exit::block_if_vm_exited();
3954   JVMWrapper("JVM_RawMonitorExit");
3955   ((Mutex*) mon)->jvm_raw_unlock();
3956 }
3957 
3958 
3959 // Shared JNI/JVM entry points //////////////////////////////////////////////////////////////
3960 
3961 jclass find_class_from_class_loader(JNIEnv* env, Symbol* name, jboolean init,
3962                                     Handle loader, Handle protection_domain,
3963                                     jboolean throwError, TRAPS) {
3964   // Security Note:
3965   //   The Java level wrapper will perform the necessary security check allowing
3966   //   us to pass the NULL as the initiating class loader.  The VM is responsible for
3967   //   the checkPackageAccess relative to the initiating class loader via the
3968   //   protection_domain. The protection_domain is passed as NULL by the java code
3969   //   if there is no security manager in 3-arg Class.forName().
3970   Klass* klass = SystemDictionary::resolve_or_fail(name, loader, protection_domain, throwError != 0, CHECK_NULL);
3971 
3972   KlassHandle klass_handle(THREAD, klass);
3973   // Check if we should initialize the class
3974   if (init && klass_handle->oop_is_instance()) {
3975     klass_handle->initialize(CHECK_NULL);
3976   }
3977   return (jclass) JNIHandles::make_local(env, klass_handle->java_mirror());
3978 }
3979 
3980 
3981 // Method ///////////////////////////////////////////////////////////////////////////////////////////
3982 
3983 JVM_ENTRY(jobject, JVM_InvokeMethod(JNIEnv *env, jobject method, jobject obj, jobjectArray args0))
3984   JVMWrapper("JVM_InvokeMethod");
3985   Handle method_handle;
3986   if (thread->stack_available((address) &method_handle) >= JVMInvokeMethodSlack) {
3987     method_handle = Handle(THREAD, JNIHandles::resolve(method));
3988     Handle receiver(THREAD, JNIHandles::resolve(obj));
3989     objArrayHandle args(THREAD, objArrayOop(JNIHandles::resolve(args0)));
3990     oop result = Reflection::invoke_method(method_handle(), receiver, args, CHECK_NULL);
3991     jobject res = JNIHandles::make_local(env, result);
3992     if (JvmtiExport::should_post_vm_object_alloc()) {
3993       oop ret_type = java_lang_reflect_Method::return_type(method_handle());
3994       assert(ret_type != NULL, "sanity check: ret_type oop must not be NULL!");
3995       if (java_lang_Class::is_primitive(ret_type)) {
3996         // Only for primitive type vm allocates memory for java object.
3997         // See box() method.
3998         JvmtiExport::post_vm_object_alloc(JavaThread::current(), result);
3999       }
4000     }
4001     return res;
4002   } else {
4003     THROW_0(vmSymbols::java_lang_StackOverflowError());
4004   }
4005 JVM_END
4006 
4007 
4008 JVM_ENTRY(jobject, JVM_NewInstanceFromConstructor(JNIEnv *env, jobject c, jobjectArray args0))
4009   JVMWrapper("JVM_NewInstanceFromConstructor");
4010   oop constructor_mirror = JNIHandles::resolve(c);
4011   objArrayHandle args(THREAD, objArrayOop(JNIHandles::resolve(args0)));
4012   oop result = Reflection::invoke_constructor(constructor_mirror, args, CHECK_NULL);
4013   jobject res = JNIHandles::make_local(env, result);
4014   if (JvmtiExport::should_post_vm_object_alloc()) {
4015     JvmtiExport::post_vm_object_alloc(JavaThread::current(), result);
4016   }
4017   return res;
4018 JVM_END
4019 
4020 // Atomic ///////////////////////////////////////////////////////////////////////////////////////////
4021 
4022 JVM_LEAF(jboolean, JVM_SupportsCX8())
4023   JVMWrapper("JVM_SupportsCX8");
4024   return VM_Version::supports_cx8();
4025 JVM_END
4026 
4027 
4028 JVM_ENTRY(jboolean, JVM_CX8Field(JNIEnv *env, jobject obj, jfieldID fid, jlong oldVal, jlong newVal))
4029   JVMWrapper("JVM_CX8Field");
4030   jlong res;
4031   oop             o       = JNIHandles::resolve(obj);
4032   intptr_t        fldOffs = jfieldIDWorkaround::from_instance_jfieldID(o->klass(), fid);
4033   volatile jlong* addr    = (volatile jlong*)((address)o + fldOffs);
4034 
4035   assert(VM_Version::supports_cx8(), "cx8 not supported");
4036   res = Atomic::cmpxchg(newVal, addr, oldVal);
4037 
4038   return res == oldVal;
4039 JVM_END
4040 
4041 // DTrace ///////////////////////////////////////////////////////////////////
4042 
4043 JVM_ENTRY(jint, JVM_DTraceGetVersion(JNIEnv* env))
4044   JVMWrapper("JVM_DTraceGetVersion");
4045   return (jint)JVM_TRACING_DTRACE_VERSION;
4046 JVM_END
4047 
4048 JVM_ENTRY(jlong,JVM_DTraceActivate(
4049     JNIEnv* env, jint version, jstring module_name, jint providers_count,
4050     JVM_DTraceProvider* providers))
4051   JVMWrapper("JVM_DTraceActivate");
4052   return DTraceJSDT::activate(
4053     version, module_name, providers_count, providers, CHECK_0);
4054 JVM_END
4055 
4056 JVM_ENTRY(jboolean,JVM_DTraceIsProbeEnabled(JNIEnv* env, jmethodID method))
4057   JVMWrapper("JVM_DTraceIsProbeEnabled");
4058   return DTraceJSDT::is_probe_enabled(method);
4059 JVM_END
4060 
4061 JVM_ENTRY(void,JVM_DTraceDispose(JNIEnv* env, jlong handle))
4062   JVMWrapper("JVM_DTraceDispose");
4063   DTraceJSDT::dispose(handle);
4064 JVM_END
4065 
4066 JVM_ENTRY(jboolean,JVM_DTraceIsSupported(JNIEnv* env))
4067   JVMWrapper("JVM_DTraceIsSupported");
4068   return DTraceJSDT::is_supported();
4069 JVM_END
4070 
4071 // Returns an array of all live Thread objects (VM internal JavaThreads,
4072 // jvmti agent threads, and JNI attaching threads  are skipped)
4073 // See CR 6404306 regarding JNI attaching threads
4074 JVM_ENTRY(jobjectArray, JVM_GetAllThreads(JNIEnv *env, jclass dummy))
4075   ResourceMark rm(THREAD);
4076   ThreadsListEnumerator tle(THREAD, false, false);
4077   JvmtiVMObjectAllocEventCollector oam;
4078 
4079   int num_threads = tle.num_threads();
4080   objArrayOop r = oopFactory::new_objArray(SystemDictionary::Thread_klass(), num_threads, CHECK_NULL);
4081   objArrayHandle threads_ah(THREAD, r);
4082 
4083   for (int i = 0; i < num_threads; i++) {
4084     Handle h = tle.get_threadObj(i);
4085     threads_ah->obj_at_put(i, h());
4086   }
4087 
4088   return (jobjectArray) JNIHandles::make_local(env, threads_ah());
4089 JVM_END
4090 
4091 
4092 // Support for java.lang.Thread.getStackTrace() and getAllStackTraces() methods
4093 // Return StackTraceElement[][], each element is the stack trace of a thread in
4094 // the corresponding entry in the given threads array
4095 JVM_ENTRY(jobjectArray, JVM_DumpThreads(JNIEnv *env, jclass threadClass, jobjectArray threads))
4096   JVMWrapper("JVM_DumpThreads");
4097   JvmtiVMObjectAllocEventCollector oam;
4098 
4099   // Check if threads is null
4100   if (threads == NULL) {
4101     THROW_(vmSymbols::java_lang_NullPointerException(), 0);
4102   }
4103 
4104   objArrayOop a = objArrayOop(JNIHandles::resolve_non_null(threads));
4105   objArrayHandle ah(THREAD, a);
4106   int num_threads = ah->length();
4107   // check if threads is non-empty array
4108   if (num_threads == 0) {
4109     THROW_(vmSymbols::java_lang_IllegalArgumentException(), 0);
4110   }
4111 
4112   // check if threads is not an array of objects of Thread class
4113   Klass* k = ObjArrayKlass::cast(ah->klass())->element_klass();
4114   if (k != SystemDictionary::Thread_klass()) {
4115     THROW_(vmSymbols::java_lang_IllegalArgumentException(), 0);
4116   }
4117 
4118   ResourceMark rm(THREAD);
4119 
4120   GrowableArray<instanceHandle>* thread_handle_array = new GrowableArray<instanceHandle>(num_threads);
4121   for (int i = 0; i < num_threads; i++) {
4122     oop thread_obj = ah->obj_at(i);
4123     instanceHandle h(THREAD, (instanceOop) thread_obj);
4124     thread_handle_array->append(h);
4125   }
4126 
4127   Handle stacktraces = ThreadService::dump_stack_traces(thread_handle_array, num_threads, CHECK_NULL);
4128   return (jobjectArray)JNIHandles::make_local(env, stacktraces());
4129 
4130 JVM_END
4131 
4132 // JVM monitoring and management support
4133 JVM_ENTRY_NO_ENV(void*, JVM_GetManagement(jint version))
4134   return Management::get_jmm_interface(version);
4135 JVM_END
4136 
4137 // com.sun.tools.attach.VirtualMachine agent properties support
4138 //
4139 // Initialize the agent properties with the properties maintained in the VM
4140 JVM_ENTRY(jobject, JVM_InitAgentProperties(JNIEnv *env, jobject properties))
4141   JVMWrapper("JVM_InitAgentProperties");
4142   ResourceMark rm;
4143 
4144   Handle props(THREAD, JNIHandles::resolve_non_null(properties));
4145 
4146   PUTPROP(props, "sun.java.command", Arguments::java_command());
4147   PUTPROP(props, "sun.jvm.flags", Arguments::jvm_flags());
4148   PUTPROP(props, "sun.jvm.args", Arguments::jvm_args());
4149   return properties;
4150 JVM_END
4151 
4152 JVM_ENTRY(jobjectArray, JVM_GetEnclosingMethodInfo(JNIEnv *env, jclass ofClass))
4153 {
4154   JVMWrapper("JVM_GetEnclosingMethodInfo");
4155   JvmtiVMObjectAllocEventCollector oam;
4156 
4157   if (ofClass == NULL) {
4158     return NULL;
4159   }
4160   Handle mirror(THREAD, JNIHandles::resolve_non_null(ofClass));
4161   // Special handling for primitive objects
4162   if (java_lang_Class::is_primitive(mirror())) {
4163     return NULL;
4164   }
4165   Klass* k = java_lang_Class::as_Klass(mirror());
4166   if (!k->oop_is_instance()) {
4167     return NULL;
4168   }
4169   instanceKlassHandle ik_h(THREAD, k);
4170   int encl_method_class_idx = ik_h->enclosing_method_class_index();
4171   if (encl_method_class_idx == 0) {
4172     return NULL;
4173   }
4174   objArrayOop dest_o = oopFactory::new_objArray(SystemDictionary::Object_klass(), 3, CHECK_NULL);
4175   objArrayHandle dest(THREAD, dest_o);
4176   Klass* enc_k = ik_h->constants()->klass_at(encl_method_class_idx, CHECK_NULL);
4177   dest->obj_at_put(0, enc_k->java_mirror());
4178   int encl_method_method_idx = ik_h->enclosing_method_method_index();
4179   if (encl_method_method_idx != 0) {
4180     Symbol* sym = ik_h->constants()->symbol_at(
4181                         extract_low_short_from_int(
4182                           ik_h->constants()->name_and_type_at(encl_method_method_idx)));
4183     Handle str = java_lang_String::create_from_symbol(sym, CHECK_NULL);
4184     dest->obj_at_put(1, str());
4185     sym = ik_h->constants()->symbol_at(
4186               extract_high_short_from_int(
4187                 ik_h->constants()->name_and_type_at(encl_method_method_idx)));
4188     str = java_lang_String::create_from_symbol(sym, CHECK_NULL);
4189     dest->obj_at_put(2, str());
4190   }
4191   return (jobjectArray) JNIHandles::make_local(dest());
4192 }
4193 JVM_END
4194 
4195 JVM_ENTRY(jintArray, JVM_GetThreadStateValues(JNIEnv* env,
4196                                               jint javaThreadState))
4197 {
4198   // If new thread states are added in future JDK and VM versions,
4199   // this should check if the JDK version is compatible with thread
4200   // states supported by the VM.  Return NULL if not compatible.
4201   //
4202   // This function must map the VM java_lang_Thread::ThreadStatus
4203   // to the Java thread state that the JDK supports.
4204   //
4205 
4206   typeArrayHandle values_h;
4207   switch (javaThreadState) {
4208     case JAVA_THREAD_STATE_NEW : {
4209       typeArrayOop r = oopFactory::new_typeArray(T_INT, 1, CHECK_NULL);
4210       values_h = typeArrayHandle(THREAD, r);
4211       values_h->int_at_put(0, java_lang_Thread::NEW);
4212       break;
4213     }
4214     case JAVA_THREAD_STATE_RUNNABLE : {
4215       typeArrayOop r = oopFactory::new_typeArray(T_INT, 1, CHECK_NULL);
4216       values_h = typeArrayHandle(THREAD, r);
4217       values_h->int_at_put(0, java_lang_Thread::RUNNABLE);
4218       break;
4219     }
4220     case JAVA_THREAD_STATE_BLOCKED : {
4221       typeArrayOop r = oopFactory::new_typeArray(T_INT, 1, CHECK_NULL);
4222       values_h = typeArrayHandle(THREAD, r);
4223       values_h->int_at_put(0, java_lang_Thread::BLOCKED_ON_MONITOR_ENTER);
4224       break;
4225     }
4226     case JAVA_THREAD_STATE_WAITING : {
4227       typeArrayOop r = oopFactory::new_typeArray(T_INT, 2, CHECK_NULL);
4228       values_h = typeArrayHandle(THREAD, r);
4229       values_h->int_at_put(0, java_lang_Thread::IN_OBJECT_WAIT);
4230       values_h->int_at_put(1, java_lang_Thread::PARKED);
4231       break;
4232     }
4233     case JAVA_THREAD_STATE_TIMED_WAITING : {
4234       typeArrayOop r = oopFactory::new_typeArray(T_INT, 3, CHECK_NULL);
4235       values_h = typeArrayHandle(THREAD, r);
4236       values_h->int_at_put(0, java_lang_Thread::SLEEPING);
4237       values_h->int_at_put(1, java_lang_Thread::IN_OBJECT_WAIT_TIMED);
4238       values_h->int_at_put(2, java_lang_Thread::PARKED_TIMED);
4239       break;
4240     }
4241     case JAVA_THREAD_STATE_TERMINATED : {
4242       typeArrayOop r = oopFactory::new_typeArray(T_INT, 1, CHECK_NULL);
4243       values_h = typeArrayHandle(THREAD, r);
4244       values_h->int_at_put(0, java_lang_Thread::TERMINATED);
4245       break;
4246     }
4247     default:
4248       // Unknown state - probably incompatible JDK version
4249       return NULL;
4250   }
4251 
4252   return (jintArray) JNIHandles::make_local(env, values_h());
4253 }
4254 JVM_END
4255 
4256 
4257 JVM_ENTRY(jobjectArray, JVM_GetThreadStateNames(JNIEnv* env,
4258                                                 jint javaThreadState,
4259                                                 jintArray values))
4260 {
4261   // If new thread states are added in future JDK and VM versions,
4262   // this should check if the JDK version is compatible with thread
4263   // states supported by the VM.  Return NULL if not compatible.
4264   //
4265   // This function must map the VM java_lang_Thread::ThreadStatus
4266   // to the Java thread state that the JDK supports.
4267   //
4268 
4269   ResourceMark rm;
4270 
4271   // Check if threads is null
4272   if (values == NULL) {
4273     THROW_(vmSymbols::java_lang_NullPointerException(), 0);
4274   }
4275 
4276   typeArrayOop v = typeArrayOop(JNIHandles::resolve_non_null(values));
4277   typeArrayHandle values_h(THREAD, v);
4278 
4279   objArrayHandle names_h;
4280   switch (javaThreadState) {
4281     case JAVA_THREAD_STATE_NEW : {
4282       assert(values_h->length() == 1 &&
4283                values_h->int_at(0) == java_lang_Thread::NEW,
4284              "Invalid threadStatus value");
4285 
4286       objArrayOop r = oopFactory::new_objArray(SystemDictionary::String_klass(),
4287                                                1, /* only 1 substate */
4288                                                CHECK_NULL);
4289       names_h = objArrayHandle(THREAD, r);
4290       Handle name = java_lang_String::create_from_str("NEW", CHECK_NULL);
4291       names_h->obj_at_put(0, name());
4292       break;
4293     }
4294     case JAVA_THREAD_STATE_RUNNABLE : {
4295       assert(values_h->length() == 1 &&
4296                values_h->int_at(0) == java_lang_Thread::RUNNABLE,
4297              "Invalid threadStatus value");
4298 
4299       objArrayOop r = oopFactory::new_objArray(SystemDictionary::String_klass(),
4300                                                1, /* only 1 substate */
4301                                                CHECK_NULL);
4302       names_h = objArrayHandle(THREAD, r);
4303       Handle name = java_lang_String::create_from_str("RUNNABLE", CHECK_NULL);
4304       names_h->obj_at_put(0, name());
4305       break;
4306     }
4307     case JAVA_THREAD_STATE_BLOCKED : {
4308       assert(values_h->length() == 1 &&
4309                values_h->int_at(0) == java_lang_Thread::BLOCKED_ON_MONITOR_ENTER,
4310              "Invalid threadStatus value");
4311 
4312       objArrayOop r = oopFactory::new_objArray(SystemDictionary::String_klass(),
4313                                                1, /* only 1 substate */
4314                                                CHECK_NULL);
4315       names_h = objArrayHandle(THREAD, r);
4316       Handle name = java_lang_String::create_from_str("BLOCKED", CHECK_NULL);
4317       names_h->obj_at_put(0, name());
4318       break;
4319     }
4320     case JAVA_THREAD_STATE_WAITING : {
4321       assert(values_h->length() == 2 &&
4322                values_h->int_at(0) == java_lang_Thread::IN_OBJECT_WAIT &&
4323                values_h->int_at(1) == java_lang_Thread::PARKED,
4324              "Invalid threadStatus value");
4325       objArrayOop r = oopFactory::new_objArray(SystemDictionary::String_klass(),
4326                                                2, /* number of substates */
4327                                                CHECK_NULL);
4328       names_h = objArrayHandle(THREAD, r);
4329       Handle name0 = java_lang_String::create_from_str("WAITING.OBJECT_WAIT",
4330                                                        CHECK_NULL);
4331       Handle name1 = java_lang_String::create_from_str("WAITING.PARKED",
4332                                                        CHECK_NULL);
4333       names_h->obj_at_put(0, name0());
4334       names_h->obj_at_put(1, name1());
4335       break;
4336     }
4337     case JAVA_THREAD_STATE_TIMED_WAITING : {
4338       assert(values_h->length() == 3 &&
4339                values_h->int_at(0) == java_lang_Thread::SLEEPING &&
4340                values_h->int_at(1) == java_lang_Thread::IN_OBJECT_WAIT_TIMED &&
4341                values_h->int_at(2) == java_lang_Thread::PARKED_TIMED,
4342              "Invalid threadStatus value");
4343       objArrayOop r = oopFactory::new_objArray(SystemDictionary::String_klass(),
4344                                                3, /* number of substates */
4345                                                CHECK_NULL);
4346       names_h = objArrayHandle(THREAD, r);
4347       Handle name0 = java_lang_String::create_from_str("TIMED_WAITING.SLEEPING",
4348                                                        CHECK_NULL);
4349       Handle name1 = java_lang_String::create_from_str("TIMED_WAITING.OBJECT_WAIT",
4350                                                        CHECK_NULL);
4351       Handle name2 = java_lang_String::create_from_str("TIMED_WAITING.PARKED",
4352                                                        CHECK_NULL);
4353       names_h->obj_at_put(0, name0());
4354       names_h->obj_at_put(1, name1());
4355       names_h->obj_at_put(2, name2());
4356       break;
4357     }
4358     case JAVA_THREAD_STATE_TERMINATED : {
4359       assert(values_h->length() == 1 &&
4360                values_h->int_at(0) == java_lang_Thread::TERMINATED,
4361              "Invalid threadStatus value");
4362       objArrayOop r = oopFactory::new_objArray(SystemDictionary::String_klass(),
4363                                                1, /* only 1 substate */
4364                                                CHECK_NULL);
4365       names_h = objArrayHandle(THREAD, r);
4366       Handle name = java_lang_String::create_from_str("TERMINATED", CHECK_NULL);
4367       names_h->obj_at_put(0, name());
4368       break;
4369     }
4370     default:
4371       // Unknown state - probably incompatible JDK version
4372       return NULL;
4373   }
4374   return (jobjectArray) JNIHandles::make_local(env, names_h());
4375 }
4376 JVM_END
4377 
4378 JVM_ENTRY(void, JVM_GetVersionInfo(JNIEnv* env, jvm_version_info* info, size_t info_size))
4379 {
4380   memset(info, 0, info_size);
4381 
4382   info->jvm_version = Abstract_VM_Version::jvm_version();
4383   info->update_version = 0;          /* 0 in HotSpot Express VM */
4384   info->special_update_version = 0;  /* 0 in HotSpot Express VM */
4385 
4386   // when we add a new capability in the jvm_version_info struct, we should also
4387   // consider to expose this new capability in the sun.rt.jvmCapabilities jvmstat
4388   // counter defined in runtimeService.cpp.
4389   info->is_attachable = AttachListener::is_attach_supported();
4390 }
4391 JVM_END