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