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