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