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