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