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