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