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