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