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