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