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