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 or illegal.
 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   assert(UTF8::is_legal_utf8((const unsigned char*)name, (int)strlen(name), false), "illegal UTF name");
 820 
 821   TempNewSymbol h_name = SymbolTable::new_symbol(name);
 822   Klass* k = SystemDictionary::resolve_or_null(h_name, CHECK_NULL);
 823   if (k == NULL) {
 824     return NULL;
 825   }
 826 
 827   if (log_is_enabled(Debug, class, resolve)) {
 828     trace_class_resolution(k);
 829   }
 830   return (jclass) JNIHandles::make_local(env, k->java_mirror());
 831 JVM_END
 832 
 833 // Find a class with this name in this loader, using the caller's protection domain.
 834 JVM_ENTRY(jclass, JVM_FindClassFromCaller(JNIEnv* env, const char* name,
 835                                           jboolean init, jobject loader,
 836                                           jclass caller))
 837   JVMWrapper("JVM_FindClassFromCaller throws ClassNotFoundException");
 838 
 839   TempNewSymbol h_name =
 840        SystemDictionary::class_name_symbol(name, vmSymbols::java_lang_ClassNotFoundException(),
 841                                            CHECK_NULL);
 842 
 843   oop loader_oop = JNIHandles::resolve(loader);
 844   oop from_class = JNIHandles::resolve(caller);
 845   oop protection_domain = NULL;
 846   // If loader is null, shouldn't call ClassLoader.checkPackageAccess; otherwise get
 847   // NPE. Put it in another way, the bootstrap class loader has all permission and
 848   // thus no checkPackageAccess equivalence in the VM class loader.
 849   // The caller is also passed as NULL by the java code if there is no security
 850   // manager to avoid the performance cost of getting the calling class.
 851   if (from_class != NULL && loader_oop != NULL) {
 852     protection_domain = java_lang_Class::as_Klass(from_class)->protection_domain();
 853   }
 854 
 855   Handle h_loader(THREAD, loader_oop);
 856   Handle h_prot(THREAD, protection_domain);
 857   jclass result = find_class_from_class_loader(env, h_name, init, h_loader,
 858                                                h_prot, false, THREAD);
 859 
 860   if (log_is_enabled(Debug, class, resolve) && result != NULL) {
 861     trace_class_resolution(java_lang_Class::as_Klass(JNIHandles::resolve_non_null(result)));
 862   }
 863   return result;
 864 JVM_END
 865 
 866 // Currently only called from the old verifier.
 867 JVM_ENTRY(jclass, JVM_FindClassFromClass(JNIEnv *env, const char *name,
 868                                          jboolean init, jclass from))
 869   JVMWrapper("JVM_FindClassFromClass");
 870   TempNewSymbol h_name =
 871        SystemDictionary::class_name_symbol(name, vmSymbols::java_lang_ClassNotFoundException(),
 872                                            CHECK_NULL);
 873   oop from_class_oop = JNIHandles::resolve(from);
 874   Klass* from_class = (from_class_oop == NULL)
 875                            ? (Klass*)NULL
 876                            : java_lang_Class::as_Klass(from_class_oop);
 877   oop class_loader = NULL;
 878   oop protection_domain = NULL;
 879   if (from_class != NULL) {
 880     class_loader = from_class->class_loader();
 881     protection_domain = from_class->protection_domain();
 882   }
 883   Handle h_loader(THREAD, class_loader);
 884   Handle h_prot  (THREAD, protection_domain);
 885   jclass result = find_class_from_class_loader(env, h_name, init, h_loader,
 886                                                h_prot, true, thread);
 887 
 888   if (log_is_enabled(Debug, class, resolve) && result != NULL) {
 889     // this function is generally only used for class loading during verification.
 890     ResourceMark rm;
 891     oop from_mirror = JNIHandles::resolve_non_null(from);
 892     Klass* from_class = java_lang_Class::as_Klass(from_mirror);
 893     const char * from_name = from_class->external_name();
 894 
 895     oop mirror = JNIHandles::resolve_non_null(result);
 896     Klass* to_class = java_lang_Class::as_Klass(mirror);
 897     const char * to = to_class->external_name();
 898     log_debug(class, resolve)("%s %s (verification)", from_name, to);
 899   }
 900 
 901   return result;
 902 JVM_END
 903 
 904 static void is_lock_held_by_thread(Handle loader, PerfCounter* counter, TRAPS) {
 905   if (loader.is_null()) {
 906     return;
 907   }
 908 
 909   // check whether the current caller thread holds the lock or not.
 910   // If not, increment the corresponding counter
 911   if (ObjectSynchronizer::query_lock_ownership((JavaThread*)THREAD, loader) !=
 912       ObjectSynchronizer::owner_self) {
 913     counter->inc();
 914   }
 915 }
 916 
 917 // common code for JVM_DefineClass() and JVM_DefineClassWithSource()
 918 static jclass jvm_define_class_common(JNIEnv *env, const char *name,
 919                                       jobject loader, const jbyte *buf,
 920                                       jsize len, jobject pd, const char *source,
 921                                       TRAPS) {
 922   if (source == NULL)  source = "__JVM_DefineClass__";
 923 
 924   assert(THREAD->is_Java_thread(), "must be a JavaThread");
 925   JavaThread* jt = (JavaThread*) THREAD;
 926 
 927   PerfClassTraceTime vmtimer(ClassLoader::perf_define_appclass_time(),
 928                              ClassLoader::perf_define_appclass_selftime(),
 929                              ClassLoader::perf_define_appclasses(),
 930                              jt->get_thread_stat()->perf_recursion_counts_addr(),
 931                              jt->get_thread_stat()->perf_timers_addr(),
 932                              PerfClassTraceTime::DEFINE_CLASS);
 933 
 934   if (UsePerfData) {
 935     ClassLoader::perf_app_classfile_bytes_read()->inc(len);
 936   }
 937 
 938   // Class resolution will get the class name from the .class stream if the name is null.
 939   TempNewSymbol class_name = name == NULL ? NULL :
 940        SystemDictionary::class_name_symbol(name, vmSymbols::java_lang_NoClassDefFoundError(),
 941                                            CHECK_NULL);
 942 
 943   ResourceMark rm(THREAD);
 944   ClassFileStream st((u1*)buf, len, source, ClassFileStream::verify);
 945   Handle class_loader (THREAD, JNIHandles::resolve(loader));
 946   if (UsePerfData) {
 947     is_lock_held_by_thread(class_loader,
 948                            ClassLoader::sync_JVMDefineClassLockFreeCounter(),
 949                            THREAD);
 950   }
 951   Handle protection_domain (THREAD, JNIHandles::resolve(pd));
 952   Klass* k = SystemDictionary::resolve_from_stream(class_name,
 953                                                    class_loader,
 954                                                    protection_domain,
 955                                                    &st,
 956                                                    CHECK_NULL);
 957 
 958   if (log_is_enabled(Debug, class, resolve) && k != NULL) {
 959     trace_class_resolution(k);
 960   }
 961 
 962   return (jclass) JNIHandles::make_local(env, k->java_mirror());
 963 }
 964 
 965 enum {
 966   NESTMATE              = java_lang_invoke_MemberName::MN_NESTMATE_CLASS,
 967   HIDDEN_CLASS          = java_lang_invoke_MemberName::MN_HIDDEN_CLASS,
 968   STRONG_LOADER_LINK    = java_lang_invoke_MemberName::MN_STRONG_LOADER_LINK,
 969   ACCESS_VM_ANNOTATIONS = java_lang_invoke_MemberName::MN_ACCESS_VM_ANNOTATIONS
 970 };
 971 
 972 /*
 973  * Define a class with the specified flags that indicates if it's a nestmate,
 974  * hidden, or strongly referenced from class loader.
 975  */
 976 static jclass jvm_lookup_define_class(JNIEnv *env, jclass lookup, const char *name,
 977                                       const jbyte *buf, jsize len, jobject pd,
 978                                       jboolean init, int flags, jobject classData, TRAPS) {
 979   assert(THREAD->is_Java_thread(), "must be a JavaThread");
 980   JavaThread* jt = (JavaThread*) THREAD;
 981   ResourceMark rm(THREAD);
 982 
 983   Klass* lookup_k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(lookup));
 984   // Lookup class must be a non-null instance
 985   if (lookup_k == NULL) {
 986     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Lookup class is null");
 987   }
 988   assert(lookup_k->is_instance_klass(), "Lookup class must be an instance klass");
 989 
 990   Handle class_loader (THREAD, lookup_k->class_loader());
 991 
 992   bool is_nestmate = (flags & NESTMATE) == NESTMATE;
 993   bool is_hidden = (flags & HIDDEN_CLASS) == HIDDEN_CLASS;
 994   bool is_strong = (flags & STRONG_LOADER_LINK) == STRONG_LOADER_LINK;
 995   bool vm_annotations = (flags & ACCESS_VM_ANNOTATIONS) == ACCESS_VM_ANNOTATIONS;
 996 
 997   InstanceKlass* host_class = NULL;
 998   if (is_nestmate) {
 999     host_class = InstanceKlass::cast(lookup_k)->nest_host(CHECK_NULL);
1000   }
1001 
1002   log_info(class, nestmates)("LookupDefineClass: %s - %s%s, %s, %s, %s",
1003                              name,
1004                              is_nestmate ? "with dynamic nest-host " : "non-nestmate",
1005                              is_nestmate ? host_class->external_name() : "",
1006                              is_hidden ? "hidden" : "not hidden",
1007                              is_strong ? "strong" : "weak",
1008                              vm_annotations ? "with vm annotations" : "without vm annotation");
1009 
1010   if (!is_hidden) {
1011     // classData is only applicable for hidden classes
1012     if (classData != NULL) {
1013       THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "classData is only applicable for hidden classes");
1014     }
1015     if (is_nestmate) {
1016       THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "dynamic nestmate is only applicable for hidden classes");
1017     }
1018     if (!is_strong) {
1019       THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "an ordinary class must be strongly referenced by its defining loader");
1020     }
1021     if (vm_annotations) {
1022       THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "vm annotations only allowed for hidden classes");
1023     }
1024     if (flags != STRONG_LOADER_LINK) {
1025       THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
1026                   err_msg("invalid flag 0x%x", flags));
1027     }
1028   }
1029 
1030   // Class resolution will get the class name from the .class stream if the name is null.
1031   TempNewSymbol class_name = name == NULL ? NULL :
1032        SystemDictionary::class_name_symbol(name, vmSymbols::java_lang_NoClassDefFoundError(),
1033                                            CHECK_NULL);
1034 
1035   Handle protection_domain (THREAD, JNIHandles::resolve(pd));
1036   const char* source = is_nestmate ? host_class->external_name() : "__JVM_LookupDefineClass__";
1037   ClassFileStream st((u1*)buf, len, source, ClassFileStream::verify);
1038 
1039   Klass* defined_k;
1040   InstanceKlass* ik = NULL;
1041   if (!is_hidden) {
1042     defined_k = SystemDictionary::resolve_from_stream(class_name,
1043                                                       class_loader,
1044                                                       protection_domain,
1045                                                       &st,
1046                                                       CHECK_NULL);
1047 
1048     if (log_is_enabled(Debug, class, resolve) && defined_k != NULL) {
1049       trace_class_resolution(defined_k);
1050     }
1051     ik = InstanceKlass::cast(defined_k);
1052   } else { // hidden
1053     Handle classData_h(THREAD, JNIHandles::resolve(classData));
1054     ClassLoadInfo cl_info(protection_domain,
1055                           NULL, // unsafe_anonymous_host
1056                           NULL, // cp_patches
1057                           host_class,
1058                           classData_h,
1059                           is_hidden,
1060                           is_strong,
1061                           vm_annotations);
1062     defined_k = SystemDictionary::parse_stream(class_name,
1063                                                class_loader,
1064                                                &st,
1065                                                cl_info,
1066                                                CHECK_NULL);
1067     if (defined_k == NULL) {
1068       THROW_MSG_0(vmSymbols::java_lang_Error(), "Failure to define a hidden class");
1069     }
1070 
1071     ik = InstanceKlass::cast(defined_k);
1072 
1073     // The hidden class loader data has been artificially been kept alive to
1074     // this point. The mirror and any instances of this class have to keep
1075     // it alive afterwards.
1076     ik->class_loader_data()->dec_keep_alive();
1077 
1078     if (is_nestmate && log_is_enabled(Debug, class, nestmates)) {
1079       ModuleEntry* module = ik->module();
1080       const char * module_name = module->is_named() ? module->name()->as_C_string() : UNNAMED_MODULE;
1081       log_debug(class, nestmates)("Dynamic nestmate: %s/%s, nest_host %s, %s",
1082                                   module_name,
1083                                   ik->external_name(),
1084                                   host_class->external_name(),
1085                                   ik->is_hidden() ? "is hidden" : "is not hidden");
1086     }
1087   }
1088   assert(Reflection::is_same_class_package(lookup_k, defined_k),
1089          "lookup class and defined class are in different packages");
1090 
1091   if (init) {
1092     ik->initialize(CHECK_NULL);
1093   } else {
1094     ik->link_class(CHECK_NULL);
1095   }
1096 
1097   return (jclass) JNIHandles::make_local(env, defined_k->java_mirror());
1098 }
1099 
1100 JVM_ENTRY(jclass, JVM_DefineClass(JNIEnv *env, const char *name, jobject loader, const jbyte *buf, jsize len, jobject pd))
1101   JVMWrapper("JVM_DefineClass");
1102 
1103   return jvm_define_class_common(env, name, loader, buf, len, pd, NULL, THREAD);
1104 JVM_END
1105 
1106 /*
1107  * Define a class with the specified lookup class.
1108  *  lookup:  Lookup class
1109  *  name:    the name of the class
1110  *  buf:     class bytes
1111  *  len:     length of class bytes
1112  *  pd:      protection domain
1113  *  init:    initialize the class
1114  *  flags:   properties of the class
1115  *  classData: private static pre-initialized field
1116  */
1117 JVM_ENTRY(jclass, JVM_LookupDefineClass(JNIEnv *env, jclass lookup, const char *name, const jbyte *buf,
1118           jsize len, jobject pd, jboolean initialize, int flags, jobject classData))
1119   JVMWrapper("JVM_LookupDefineClass");
1120 
1121   if (lookup == NULL) {
1122     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Lookup class is null");
1123   }
1124 
1125   assert(buf != NULL, "buf must not be NULL");
1126 
1127   return jvm_lookup_define_class(env, lookup, name, buf, len, pd, initialize, flags, classData, THREAD);
1128 JVM_END
1129 
1130 JVM_ENTRY(jclass, JVM_DefineClassWithSource(JNIEnv *env, const char *name, jobject loader, const jbyte *buf, jsize len, jobject pd, const char *source))
1131   JVMWrapper("JVM_DefineClassWithSource");
1132 
1133   return jvm_define_class_common(env, name, loader, buf, len, pd, source, THREAD);
1134 JVM_END
1135 
1136 JVM_ENTRY(jclass, JVM_FindLoadedClass(JNIEnv *env, jobject loader, jstring name))
1137   JVMWrapper("JVM_FindLoadedClass");
1138   ResourceMark rm(THREAD);
1139 
1140   Handle h_name (THREAD, JNIHandles::resolve_non_null(name));
1141   char* str = java_lang_String::as_utf8_string(h_name());
1142 
1143   // Sanity check, don't expect null
1144   if (str == NULL) return NULL;
1145 
1146   // Internalize the string, converting '.' to '/' in string.
1147   char* p = (char*)str;
1148   while (*p != '\0') {
1149       if (*p == '.') {
1150           *p = '/';
1151       }
1152       p++;
1153   }
1154 
1155   const int str_len = (int)(p - str);
1156   if (str_len > Symbol::max_length()) {
1157     // It's impossible to create this class;  the name cannot fit
1158     // into the constant pool.
1159     return NULL;
1160   }
1161   TempNewSymbol klass_name = SymbolTable::new_symbol(str, str_len);
1162 
1163   // Security Note:
1164   //   The Java level wrapper will perform the necessary security check allowing
1165   //   us to pass the NULL as the initiating class loader.
1166   Handle h_loader(THREAD, JNIHandles::resolve(loader));
1167   if (UsePerfData) {
1168     is_lock_held_by_thread(h_loader,
1169                            ClassLoader::sync_JVMFindLoadedClassLockFreeCounter(),
1170                            THREAD);
1171   }
1172 
1173   Klass* k = SystemDictionary::find_instance_or_array_klass(klass_name,
1174                                                               h_loader,
1175                                                               Handle(),
1176                                                               CHECK_NULL);
1177 #if INCLUDE_CDS
1178   if (k == NULL) {
1179     // If the class is not already loaded, try to see if it's in the shared
1180     // archive for the current classloader (h_loader).
1181     k = SystemDictionaryShared::find_or_load_shared_class(klass_name, h_loader, CHECK_NULL);
1182   }
1183 #endif
1184   return (k == NULL) ? NULL :
1185             (jclass) JNIHandles::make_local(env, k->java_mirror());
1186 JVM_END
1187 
1188 // Module support //////////////////////////////////////////////////////////////////////////////
1189 
1190 JVM_ENTRY(void, JVM_DefineModule(JNIEnv *env, jobject module, jboolean is_open, jstring version,
1191                                  jstring location, jobjectArray packages))
1192   JVMWrapper("JVM_DefineModule");
1193   Modules::define_module(module, is_open, version, location, packages, CHECK);
1194 JVM_END
1195 
1196 JVM_ENTRY(void, JVM_SetBootLoaderUnnamedModule(JNIEnv *env, jobject module))
1197   JVMWrapper("JVM_SetBootLoaderUnnamedModule");
1198   Modules::set_bootloader_unnamed_module(module, CHECK);
1199 JVM_END
1200 
1201 JVM_ENTRY(void, JVM_AddModuleExports(JNIEnv *env, jobject from_module, jstring package, jobject to_module))
1202   JVMWrapper("JVM_AddModuleExports");
1203   Modules::add_module_exports_qualified(from_module, package, to_module, CHECK);
1204 JVM_END
1205 
1206 JVM_ENTRY(void, JVM_AddModuleExportsToAllUnnamed(JNIEnv *env, jobject from_module, jstring package))
1207   JVMWrapper("JVM_AddModuleExportsToAllUnnamed");
1208   Modules::add_module_exports_to_all_unnamed(from_module, package, CHECK);
1209 JVM_END
1210 
1211 JVM_ENTRY(void, JVM_AddModuleExportsToAll(JNIEnv *env, jobject from_module, jstring package))
1212   JVMWrapper("JVM_AddModuleExportsToAll");
1213   Modules::add_module_exports(from_module, package, NULL, CHECK);
1214 JVM_END
1215 
1216 JVM_ENTRY (void, JVM_AddReadsModule(JNIEnv *env, jobject from_module, jobject source_module))
1217   JVMWrapper("JVM_AddReadsModule");
1218   Modules::add_reads_module(from_module, source_module, CHECK);
1219 JVM_END
1220 
1221 // Reflection support //////////////////////////////////////////////////////////////////////////////
1222 
1223 JVM_ENTRY(jstring, JVM_InitClassName(JNIEnv *env, jclass cls))
1224   assert (cls != NULL, "illegal class");
1225   JVMWrapper("JVM_InitClassName");
1226   JvmtiVMObjectAllocEventCollector oam;
1227   ResourceMark rm(THREAD);
1228   HandleMark hm(THREAD);
1229   Handle java_class(THREAD, JNIHandles::resolve(cls));
1230   oop result = java_lang_Class::name(java_class, CHECK_NULL);
1231   return (jstring) JNIHandles::make_local(env, result);
1232 JVM_END
1233 
1234 
1235 JVM_ENTRY(jobjectArray, JVM_GetClassInterfaces(JNIEnv *env, jclass cls))
1236   JVMWrapper("JVM_GetClassInterfaces");
1237   JvmtiVMObjectAllocEventCollector oam;
1238   oop mirror = JNIHandles::resolve_non_null(cls);
1239 
1240   // Special handling for primitive objects
1241   if (java_lang_Class::is_primitive(mirror)) {
1242     // Primitive objects does not have any interfaces
1243     objArrayOop r = oopFactory::new_objArray(SystemDictionary::Class_klass(), 0, CHECK_NULL);
1244     return (jobjectArray) JNIHandles::make_local(env, r);
1245   }
1246 
1247   Klass* klass = java_lang_Class::as_Klass(mirror);
1248   // Figure size of result array
1249   int size;
1250   if (klass->is_instance_klass()) {
1251     size = InstanceKlass::cast(klass)->local_interfaces()->length();
1252   } else {
1253     assert(klass->is_objArray_klass() || klass->is_typeArray_klass(), "Illegal mirror klass");
1254     size = 2;
1255   }
1256 
1257   // Allocate result array
1258   objArrayOop r = oopFactory::new_objArray(SystemDictionary::Class_klass(), size, CHECK_NULL);
1259   objArrayHandle result (THREAD, r);
1260   // Fill in result
1261   if (klass->is_instance_klass()) {
1262     // Regular instance klass, fill in all local interfaces
1263     for (int index = 0; index < size; index++) {
1264       Klass* k = InstanceKlass::cast(klass)->local_interfaces()->at(index);
1265       result->obj_at_put(index, k->java_mirror());
1266     }
1267   } else {
1268     // All arrays implement java.lang.Cloneable and java.io.Serializable
1269     result->obj_at_put(0, SystemDictionary::Cloneable_klass()->java_mirror());
1270     result->obj_at_put(1, SystemDictionary::Serializable_klass()->java_mirror());
1271   }
1272   return (jobjectArray) JNIHandles::make_local(env, result());
1273 JVM_END
1274 
1275 
1276 JVM_ENTRY(jboolean, JVM_IsInterface(JNIEnv *env, jclass cls))
1277   JVMWrapper("JVM_IsInterface");
1278   oop mirror = JNIHandles::resolve_non_null(cls);
1279   if (java_lang_Class::is_primitive(mirror)) {
1280     return JNI_FALSE;
1281   }
1282   Klass* k = java_lang_Class::as_Klass(mirror);
1283   jboolean result = k->is_interface();
1284   assert(!result || k->is_instance_klass(),
1285          "all interfaces are instance types");
1286   // The compiler intrinsic for isInterface tests the
1287   // Klass::_access_flags bits in the same way.
1288   return result;
1289 JVM_END
1290 
1291 JVM_ENTRY(jboolean, JVM_IsHiddenClass(JNIEnv *env, jclass cls))
1292   JVMWrapper("JVM_IsHiddenClass");
1293   oop mirror = JNIHandles::resolve_non_null(cls);
1294   if (java_lang_Class::is_primitive(mirror)) {
1295     return JNI_FALSE;
1296   }
1297   Klass* k = java_lang_Class::as_Klass(mirror);
1298   return k->is_hidden();
1299 JVM_END
1300 
1301 JVM_ENTRY(jobjectArray, JVM_GetClassSigners(JNIEnv *env, jclass cls))
1302   JVMWrapper("JVM_GetClassSigners");
1303   JvmtiVMObjectAllocEventCollector oam;
1304   if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(cls))) {
1305     // There are no signers for primitive types
1306     return NULL;
1307   }
1308 
1309   objArrayHandle signers(THREAD, java_lang_Class::signers(JNIHandles::resolve_non_null(cls)));
1310 
1311   // If there are no signers set in the class, or if the class
1312   // is an array, return NULL.
1313   if (signers == NULL) return NULL;
1314 
1315   // copy of the signers array
1316   Klass* element = ObjArrayKlass::cast(signers->klass())->element_klass();
1317   objArrayOop signers_copy = oopFactory::new_objArray(element, signers->length(), CHECK_NULL);
1318   for (int index = 0; index < signers->length(); index++) {
1319     signers_copy->obj_at_put(index, signers->obj_at(index));
1320   }
1321 
1322   // return the copy
1323   return (jobjectArray) JNIHandles::make_local(env, signers_copy);
1324 JVM_END
1325 
1326 
1327 JVM_ENTRY(void, JVM_SetClassSigners(JNIEnv *env, jclass cls, jobjectArray signers))
1328   JVMWrapper("JVM_SetClassSigners");
1329   if (!java_lang_Class::is_primitive(JNIHandles::resolve_non_null(cls))) {
1330     // This call is ignored for primitive types and arrays.
1331     // Signers are only set once, ClassLoader.java, and thus shouldn't
1332     // be called with an array.  Only the bootstrap loader creates arrays.
1333     Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
1334     if (k->is_instance_klass()) {
1335       java_lang_Class::set_signers(k->java_mirror(), objArrayOop(JNIHandles::resolve(signers)));
1336     }
1337   }
1338 JVM_END
1339 
1340 
1341 JVM_ENTRY(jobject, JVM_GetProtectionDomain(JNIEnv *env, jclass cls))
1342   JVMWrapper("JVM_GetProtectionDomain");
1343   if (JNIHandles::resolve(cls) == NULL) {
1344     THROW_(vmSymbols::java_lang_NullPointerException(), NULL);
1345   }
1346 
1347   if (java_lang_Class::is_primitive(JNIHandles::resolve(cls))) {
1348     // Primitive types does not have a protection domain.
1349     return NULL;
1350   }
1351 
1352   oop pd = java_lang_Class::protection_domain(JNIHandles::resolve(cls));
1353   return (jobject) JNIHandles::make_local(env, pd);
1354 JVM_END
1355 
1356 
1357 // Returns the inherited_access_control_context field of the running thread.
1358 JVM_ENTRY(jobject, JVM_GetInheritedAccessControlContext(JNIEnv *env, jclass cls))
1359   JVMWrapper("JVM_GetInheritedAccessControlContext");
1360   oop result = java_lang_Thread::inherited_access_control_context(thread->threadObj());
1361   return JNIHandles::make_local(env, result);
1362 JVM_END
1363 
1364 class RegisterArrayForGC {
1365  private:
1366   JavaThread *_thread;
1367  public:
1368   RegisterArrayForGC(JavaThread *thread, GrowableArray<oop>* array)  {
1369     _thread = thread;
1370     _thread->register_array_for_gc(array);
1371   }
1372 
1373   ~RegisterArrayForGC() {
1374     _thread->register_array_for_gc(NULL);
1375   }
1376 };
1377 
1378 
1379 JVM_ENTRY(jobject, JVM_GetStackAccessControlContext(JNIEnv *env, jclass cls))
1380   JVMWrapper("JVM_GetStackAccessControlContext");
1381   if (!UsePrivilegedStack) return NULL;
1382 
1383   ResourceMark rm(THREAD);
1384   GrowableArray<oop>* local_array = new GrowableArray<oop>(12);
1385   JvmtiVMObjectAllocEventCollector oam;
1386 
1387   // count the protection domains on the execution stack. We collapse
1388   // duplicate consecutive protection domains into a single one, as
1389   // well as stopping when we hit a privileged frame.
1390 
1391   oop previous_protection_domain = NULL;
1392   Handle privileged_context(thread, NULL);
1393   bool is_privileged = false;
1394   oop protection_domain = NULL;
1395 
1396   // Iterate through Java frames
1397   vframeStream vfst(thread);
1398   for(; !vfst.at_end(); vfst.next()) {
1399     // get method of frame
1400     Method* method = vfst.method();
1401 
1402     // stop at the first privileged frame
1403     if (method->method_holder() == SystemDictionary::AccessController_klass() &&
1404       method->name() == vmSymbols::executePrivileged_name())
1405     {
1406       // this frame is privileged
1407       is_privileged = true;
1408 
1409       javaVFrame *priv = vfst.asJavaVFrame();       // executePrivileged
1410 
1411       StackValueCollection* locals = priv->locals();
1412       StackValue* ctx_sv = locals->at(1); // AccessControlContext context
1413       StackValue* clr_sv = locals->at(2); // Class<?> caller
1414       assert(!ctx_sv->obj_is_scalar_replaced(), "found scalar-replaced object");
1415       assert(!clr_sv->obj_is_scalar_replaced(), "found scalar-replaced object");
1416       privileged_context    = ctx_sv->get_obj();
1417       Handle caller         = clr_sv->get_obj();
1418 
1419       Klass *caller_klass = java_lang_Class::as_Klass(caller());
1420       protection_domain  = caller_klass->protection_domain();
1421     } else {
1422       protection_domain = method->method_holder()->protection_domain();
1423     }
1424 
1425     if ((previous_protection_domain != protection_domain) && (protection_domain != NULL)) {
1426       local_array->push(protection_domain);
1427       previous_protection_domain = protection_domain;
1428     }
1429 
1430     if (is_privileged) break;
1431   }
1432 
1433 
1434   // either all the domains on the stack were system domains, or
1435   // we had a privileged system domain
1436   if (local_array->is_empty()) {
1437     if (is_privileged && privileged_context.is_null()) return NULL;
1438 
1439     oop result = java_security_AccessControlContext::create(objArrayHandle(), is_privileged, privileged_context, CHECK_NULL);
1440     return JNIHandles::make_local(env, result);
1441   }
1442 
1443   // the resource area must be registered in case of a gc
1444   RegisterArrayForGC ragc(thread, local_array);
1445   objArrayOop context = oopFactory::new_objArray(SystemDictionary::ProtectionDomain_klass(),
1446                                                  local_array->length(), CHECK_NULL);
1447   objArrayHandle h_context(thread, context);
1448   for (int index = 0; index < local_array->length(); index++) {
1449     h_context->obj_at_put(index, local_array->at(index));
1450   }
1451 
1452   oop result = java_security_AccessControlContext::create(h_context, is_privileged, privileged_context, CHECK_NULL);
1453 
1454   return JNIHandles::make_local(env, result);
1455 JVM_END
1456 
1457 
1458 JVM_ENTRY(jboolean, JVM_IsArrayClass(JNIEnv *env, jclass cls))
1459   JVMWrapper("JVM_IsArrayClass");
1460   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
1461   return (k != NULL) && k->is_array_klass() ? true : false;
1462 JVM_END
1463 
1464 
1465 JVM_ENTRY(jboolean, JVM_IsPrimitiveClass(JNIEnv *env, jclass cls))
1466   JVMWrapper("JVM_IsPrimitiveClass");
1467   oop mirror = JNIHandles::resolve_non_null(cls);
1468   return (jboolean) java_lang_Class::is_primitive(mirror);
1469 JVM_END
1470 
1471 
1472 JVM_ENTRY(jint, JVM_GetClassModifiers(JNIEnv *env, jclass cls))
1473   JVMWrapper("JVM_GetClassModifiers");
1474   if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(cls))) {
1475     // Primitive type
1476     return JVM_ACC_ABSTRACT | JVM_ACC_FINAL | JVM_ACC_PUBLIC;
1477   }
1478 
1479   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
1480   debug_only(int computed_modifiers = k->compute_modifier_flags(CHECK_0));
1481   assert(k->modifier_flags() == computed_modifiers, "modifiers cache is OK");
1482   return k->modifier_flags();
1483 JVM_END
1484 
1485 
1486 // Inner class reflection ///////////////////////////////////////////////////////////////////////////////
1487 
1488 JVM_ENTRY(jobjectArray, JVM_GetDeclaredClasses(JNIEnv *env, jclass ofClass))
1489   JvmtiVMObjectAllocEventCollector oam;
1490   // ofClass is a reference to a java_lang_Class object. The mirror object
1491   // of an InstanceKlass
1492 
1493   if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(ofClass)) ||
1494       ! java_lang_Class::as_Klass(JNIHandles::resolve_non_null(ofClass))->is_instance_klass()) {
1495     oop result = oopFactory::new_objArray(SystemDictionary::Class_klass(), 0, CHECK_NULL);
1496     return (jobjectArray)JNIHandles::make_local(env, result);
1497   }
1498 
1499   InstanceKlass* k = InstanceKlass::cast(java_lang_Class::as_Klass(JNIHandles::resolve_non_null(ofClass)));
1500   InnerClassesIterator iter(k);
1501 
1502   if (iter.length() == 0) {
1503     // Neither an inner nor outer class
1504     oop result = oopFactory::new_objArray(SystemDictionary::Class_klass(), 0, CHECK_NULL);
1505     return (jobjectArray)JNIHandles::make_local(env, result);
1506   }
1507 
1508   // find inner class info
1509   constantPoolHandle cp(thread, k->constants());
1510   int length = iter.length();
1511 
1512   // Allocate temp. result array
1513   objArrayOop r = oopFactory::new_objArray(SystemDictionary::Class_klass(), length/4, CHECK_NULL);
1514   objArrayHandle result (THREAD, r);
1515   int members = 0;
1516 
1517   for (; !iter.done(); iter.next()) {
1518     int ioff = iter.inner_class_info_index();
1519     int ooff = iter.outer_class_info_index();
1520 
1521     if (ioff != 0 && ooff != 0) {
1522       // Check to see if the name matches the class we're looking for
1523       // before attempting to find the class.
1524       if (cp->klass_name_at_matches(k, ooff)) {
1525         Klass* outer_klass = cp->klass_at(ooff, CHECK_NULL);
1526         if (outer_klass == k) {
1527            Klass* ik = cp->klass_at(ioff, CHECK_NULL);
1528            InstanceKlass* inner_klass = InstanceKlass::cast(ik);
1529 
1530            // Throws an exception if outer klass has not declared k as
1531            // an inner klass
1532            Reflection::check_for_inner_class(k, inner_klass, true, CHECK_NULL);
1533 
1534            result->obj_at_put(members, inner_klass->java_mirror());
1535            members++;
1536         }
1537       }
1538     }
1539   }
1540 
1541   if (members != length) {
1542     // Return array of right length
1543     objArrayOop res = oopFactory::new_objArray(SystemDictionary::Class_klass(), members, CHECK_NULL);
1544     for(int i = 0; i < members; i++) {
1545       res->obj_at_put(i, result->obj_at(i));
1546     }
1547     return (jobjectArray)JNIHandles::make_local(env, res);
1548   }
1549 
1550   return (jobjectArray)JNIHandles::make_local(env, result());
1551 JVM_END
1552 
1553 
1554 JVM_ENTRY(jclass, JVM_GetDeclaringClass(JNIEnv *env, jclass ofClass))
1555 {
1556   // ofClass is a reference to a java_lang_Class object.
1557   if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(ofClass)) ||
1558       ! java_lang_Class::as_Klass(JNIHandles::resolve_non_null(ofClass))->is_instance_klass()) {
1559     return NULL;
1560   }
1561 
1562   bool inner_is_member = false;
1563   Klass* outer_klass
1564     = InstanceKlass::cast(java_lang_Class::as_Klass(JNIHandles::resolve_non_null(ofClass))
1565                           )->compute_enclosing_class(&inner_is_member, CHECK_NULL);
1566   if (outer_klass == NULL)  return NULL;  // already a top-level class
1567   if (!inner_is_member)  return NULL;     // a hidden or unsafe anonymous class (inside a method)
1568   return (jclass) JNIHandles::make_local(env, outer_klass->java_mirror());
1569 }
1570 JVM_END
1571 
1572 JVM_ENTRY(jstring, JVM_GetSimpleBinaryName(JNIEnv *env, jclass cls))
1573 {
1574   oop mirror = JNIHandles::resolve_non_null(cls);
1575   if (java_lang_Class::is_primitive(mirror) ||
1576       !java_lang_Class::as_Klass(mirror)->is_instance_klass()) {
1577     return NULL;
1578   }
1579   InstanceKlass* k = InstanceKlass::cast(java_lang_Class::as_Klass(mirror));
1580   int ooff = 0, noff = 0;
1581   if (k->find_inner_classes_attr(&ooff, &noff, THREAD)) {
1582     if (noff != 0) {
1583       constantPoolHandle i_cp(thread, k->constants());
1584       Symbol* name = i_cp->symbol_at(noff);
1585       Handle str = java_lang_String::create_from_symbol(name, CHECK_NULL);
1586       return (jstring) JNIHandles::make_local(env, str());
1587     }
1588   }
1589   return NULL;
1590 }
1591 JVM_END
1592 
1593 JVM_ENTRY(jstring, JVM_GetClassSignature(JNIEnv *env, jclass cls))
1594   assert (cls != NULL, "illegal class");
1595   JVMWrapper("JVM_GetClassSignature");
1596   JvmtiVMObjectAllocEventCollector oam;
1597   ResourceMark rm(THREAD);
1598   // Return null for arrays and primatives
1599   if (!java_lang_Class::is_primitive(JNIHandles::resolve(cls))) {
1600     Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve(cls));
1601     if (k->is_instance_klass()) {
1602       Symbol* sym = InstanceKlass::cast(k)->generic_signature();
1603       if (sym == NULL) return NULL;
1604       Handle str = java_lang_String::create_from_symbol(sym, CHECK_NULL);
1605       return (jstring) JNIHandles::make_local(env, str());
1606     }
1607   }
1608   return NULL;
1609 JVM_END
1610 
1611 
1612 JVM_ENTRY(jbyteArray, JVM_GetClassAnnotations(JNIEnv *env, jclass cls))
1613   assert (cls != NULL, "illegal class");
1614   JVMWrapper("JVM_GetClassAnnotations");
1615 
1616   // Return null for arrays and primitives
1617   if (!java_lang_Class::is_primitive(JNIHandles::resolve(cls))) {
1618     Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve(cls));
1619     if (k->is_instance_klass()) {
1620       typeArrayOop a = Annotations::make_java_array(InstanceKlass::cast(k)->class_annotations(), CHECK_NULL);
1621       return (jbyteArray) JNIHandles::make_local(env, a);
1622     }
1623   }
1624   return NULL;
1625 JVM_END
1626 
1627 
1628 static bool jvm_get_field_common(jobject field, fieldDescriptor& fd, TRAPS) {
1629   // some of this code was adapted from from jni_FromReflectedField
1630 
1631   oop reflected = JNIHandles::resolve_non_null(field);
1632   oop mirror    = java_lang_reflect_Field::clazz(reflected);
1633   Klass* k    = java_lang_Class::as_Klass(mirror);
1634   int slot      = java_lang_reflect_Field::slot(reflected);
1635   int modifiers = java_lang_reflect_Field::modifiers(reflected);
1636 
1637   InstanceKlass* ik = InstanceKlass::cast(k);
1638   intptr_t offset = ik->field_offset(slot);
1639 
1640   if (modifiers & JVM_ACC_STATIC) {
1641     // for static fields we only look in the current class
1642     if (!ik->find_local_field_from_offset(offset, true, &fd)) {
1643       assert(false, "cannot find static field");
1644       return false;
1645     }
1646   } else {
1647     // for instance fields we start with the current class and work
1648     // our way up through the superclass chain
1649     if (!ik->find_field_from_offset(offset, false, &fd)) {
1650       assert(false, "cannot find instance field");
1651       return false;
1652     }
1653   }
1654   return true;
1655 }
1656 
1657 static Method* jvm_get_method_common(jobject method) {
1658   // some of this code was adapted from from jni_FromReflectedMethod
1659 
1660   oop reflected = JNIHandles::resolve_non_null(method);
1661   oop mirror    = NULL;
1662   int slot      = 0;
1663 
1664   if (reflected->klass() == SystemDictionary::reflect_Constructor_klass()) {
1665     mirror = java_lang_reflect_Constructor::clazz(reflected);
1666     slot   = java_lang_reflect_Constructor::slot(reflected);
1667   } else {
1668     assert(reflected->klass() == SystemDictionary::reflect_Method_klass(),
1669            "wrong type");
1670     mirror = java_lang_reflect_Method::clazz(reflected);
1671     slot   = java_lang_reflect_Method::slot(reflected);
1672   }
1673   Klass* k = java_lang_Class::as_Klass(mirror);
1674 
1675   Method* m = InstanceKlass::cast(k)->method_with_idnum(slot);
1676   assert(m != NULL, "cannot find method");
1677   return m;  // caller has to deal with NULL in product mode
1678 }
1679 
1680 /* Type use annotations support (JDK 1.8) */
1681 
1682 JVM_ENTRY(jbyteArray, JVM_GetClassTypeAnnotations(JNIEnv *env, jclass cls))
1683   assert (cls != NULL, "illegal class");
1684   JVMWrapper("JVM_GetClassTypeAnnotations");
1685   ResourceMark rm(THREAD);
1686   // Return null for arrays and primitives
1687   if (!java_lang_Class::is_primitive(JNIHandles::resolve(cls))) {
1688     Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve(cls));
1689     if (k->is_instance_klass()) {
1690       AnnotationArray* type_annotations = InstanceKlass::cast(k)->class_type_annotations();
1691       if (type_annotations != NULL) {
1692         typeArrayOop a = Annotations::make_java_array(type_annotations, CHECK_NULL);
1693         return (jbyteArray) JNIHandles::make_local(env, a);
1694       }
1695     }
1696   }
1697   return NULL;
1698 JVM_END
1699 
1700 JVM_ENTRY(jbyteArray, JVM_GetMethodTypeAnnotations(JNIEnv *env, jobject method))
1701   assert (method != NULL, "illegal method");
1702   JVMWrapper("JVM_GetMethodTypeAnnotations");
1703 
1704   // method is a handle to a java.lang.reflect.Method object
1705   Method* m = jvm_get_method_common(method);
1706   if (m == NULL) {
1707     return NULL;
1708   }
1709 
1710   AnnotationArray* type_annotations = m->type_annotations();
1711   if (type_annotations != NULL) {
1712     typeArrayOop a = Annotations::make_java_array(type_annotations, CHECK_NULL);
1713     return (jbyteArray) JNIHandles::make_local(env, a);
1714   }
1715 
1716   return NULL;
1717 JVM_END
1718 
1719 JVM_ENTRY(jbyteArray, JVM_GetFieldTypeAnnotations(JNIEnv *env, jobject field))
1720   assert (field != NULL, "illegal field");
1721   JVMWrapper("JVM_GetFieldTypeAnnotations");
1722 
1723   fieldDescriptor fd;
1724   bool gotFd = jvm_get_field_common(field, fd, CHECK_NULL);
1725   if (!gotFd) {
1726     return NULL;
1727   }
1728 
1729   return (jbyteArray) JNIHandles::make_local(env, Annotations::make_java_array(fd.type_annotations(), THREAD));
1730 JVM_END
1731 
1732 static void bounds_check(const constantPoolHandle& cp, jint index, TRAPS) {
1733   if (!cp->is_within_bounds(index)) {
1734     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "Constant pool index out of bounds");
1735   }
1736 }
1737 
1738 JVM_ENTRY(jobjectArray, JVM_GetMethodParameters(JNIEnv *env, jobject method))
1739 {
1740   JVMWrapper("JVM_GetMethodParameters");
1741   // method is a handle to a java.lang.reflect.Method object
1742   Method* method_ptr = jvm_get_method_common(method);
1743   methodHandle mh (THREAD, method_ptr);
1744   Handle reflected_method (THREAD, JNIHandles::resolve_non_null(method));
1745   const int num_params = mh->method_parameters_length();
1746 
1747   if (num_params < 0) {
1748     // A -1 return value from method_parameters_length means there is no
1749     // parameter data.  Return null to indicate this to the reflection
1750     // API.
1751     assert(num_params == -1, "num_params should be -1 if it is less than zero");
1752     return (jobjectArray)NULL;
1753   } else {
1754     // Otherwise, we return something up to reflection, even if it is
1755     // a zero-length array.  Why?  Because in some cases this can
1756     // trigger a MalformedParametersException.
1757 
1758     // make sure all the symbols are properly formatted
1759     for (int i = 0; i < num_params; i++) {
1760       MethodParametersElement* params = mh->method_parameters_start();
1761       int index = params[i].name_cp_index;
1762       constantPoolHandle cp(THREAD, mh->constants());
1763       bounds_check(cp, index, CHECK_NULL);
1764 
1765       if (0 != index && !mh->constants()->tag_at(index).is_utf8()) {
1766         THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
1767                     "Wrong type at constant pool index");
1768       }
1769 
1770     }
1771 
1772     objArrayOop result_oop = oopFactory::new_objArray(SystemDictionary::reflect_Parameter_klass(), num_params, CHECK_NULL);
1773     objArrayHandle result (THREAD, result_oop);
1774 
1775     for (int i = 0; i < num_params; i++) {
1776       MethodParametersElement* params = mh->method_parameters_start();
1777       // For a 0 index, give a NULL symbol
1778       Symbol* sym = 0 != params[i].name_cp_index ?
1779         mh->constants()->symbol_at(params[i].name_cp_index) : NULL;
1780       int flags = params[i].flags;
1781       oop param = Reflection::new_parameter(reflected_method, i, sym,
1782                                             flags, CHECK_NULL);
1783       result->obj_at_put(i, param);
1784     }
1785     return (jobjectArray)JNIHandles::make_local(env, result());
1786   }
1787 }
1788 JVM_END
1789 
1790 // New (JDK 1.4) reflection implementation /////////////////////////////////////
1791 
1792 JVM_ENTRY(jobjectArray, JVM_GetClassDeclaredFields(JNIEnv *env, jclass ofClass, jboolean publicOnly))
1793 {
1794   JVMWrapper("JVM_GetClassDeclaredFields");
1795   JvmtiVMObjectAllocEventCollector oam;
1796 
1797   // Exclude primitive types and array types
1798   if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(ofClass)) ||
1799       java_lang_Class::as_Klass(JNIHandles::resolve_non_null(ofClass))->is_array_klass()) {
1800     // Return empty array
1801     oop res = oopFactory::new_objArray(SystemDictionary::reflect_Field_klass(), 0, CHECK_NULL);
1802     return (jobjectArray) JNIHandles::make_local(env, res);
1803   }
1804 
1805   InstanceKlass* k = InstanceKlass::cast(java_lang_Class::as_Klass(JNIHandles::resolve_non_null(ofClass)));
1806   constantPoolHandle cp(THREAD, k->constants());
1807 
1808   // Ensure class is linked
1809   k->link_class(CHECK_NULL);
1810 
1811   // Allocate result
1812   int num_fields;
1813 
1814   if (publicOnly) {
1815     num_fields = 0;
1816     for (JavaFieldStream fs(k); !fs.done(); fs.next()) {
1817       if (fs.access_flags().is_public()) ++num_fields;
1818     }
1819   } else {
1820     num_fields = k->java_fields_count();
1821   }
1822 
1823   objArrayOop r = oopFactory::new_objArray(SystemDictionary::reflect_Field_klass(), num_fields, CHECK_NULL);
1824   objArrayHandle result (THREAD, r);
1825 
1826   int out_idx = 0;
1827   fieldDescriptor fd;
1828   for (JavaFieldStream fs(k); !fs.done(); fs.next()) {
1829     if (!publicOnly || fs.access_flags().is_public()) {
1830       fd.reinitialize(k, fs.index());
1831       oop field = Reflection::new_field(&fd, CHECK_NULL);
1832       result->obj_at_put(out_idx, field);
1833       ++out_idx;
1834     }
1835   }
1836   assert(out_idx == num_fields, "just checking");
1837   return (jobjectArray) JNIHandles::make_local(env, result());
1838 }
1839 JVM_END
1840 
1841 JVM_ENTRY(jboolean, JVM_IsRecord(JNIEnv *env, jclass cls))
1842 {
1843   JVMWrapper("JVM_IsRecord");
1844   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
1845   if (k != NULL && k->is_instance_klass()) {
1846     InstanceKlass* ik = InstanceKlass::cast(k);
1847     return ik->is_record();
1848   } else {
1849     return false;
1850   }
1851 }
1852 JVM_END
1853 
1854 JVM_ENTRY(jobjectArray, JVM_GetRecordComponents(JNIEnv* env, jclass ofClass))
1855 {
1856   JVMWrapper("JVM_GetRecordComponents");
1857   Klass* c = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(ofClass));
1858   assert(c->is_instance_klass(), "must be");
1859   InstanceKlass* ik = InstanceKlass::cast(c);
1860 
1861   if (ik->is_record()) {
1862     Array<RecordComponent*>* components = ik->record_components();
1863     assert(components != NULL, "components should not be NULL");
1864     {
1865       JvmtiVMObjectAllocEventCollector oam;
1866       constantPoolHandle cp(THREAD, ik->constants());
1867       int length = components->length();
1868       assert(length >= 0, "unexpected record_components length");
1869       objArrayOop record_components =
1870         oopFactory::new_objArray(SystemDictionary::RecordComponent_klass(), length, CHECK_NULL);
1871       objArrayHandle components_h (THREAD, record_components);
1872 
1873       for (int x = 0; x < length; x++) {
1874         RecordComponent* component = components->at(x);
1875         assert(component != NULL, "unexpected NULL record component");
1876         oop component_oop = java_lang_reflect_RecordComponent::create(ik, component, CHECK_NULL);
1877         components_h->obj_at_put(x, component_oop);
1878       }
1879       return (jobjectArray)JNIHandles::make_local(components_h());
1880     }
1881   }
1882 
1883   // Return empty array if ofClass is not a record.
1884   objArrayOop result = oopFactory::new_objArray(SystemDictionary::RecordComponent_klass(), 0, CHECK_NULL);
1885   return (jobjectArray)JNIHandles::make_local(env, result);
1886 }
1887 JVM_END
1888 
1889 static bool select_method(const methodHandle& method, bool want_constructor) {
1890   if (want_constructor) {
1891     return (method->is_initializer() && !method->is_static());
1892   } else {
1893     return  (!method->is_initializer() && !method->is_overpass());
1894   }
1895 }
1896 
1897 static jobjectArray get_class_declared_methods_helper(
1898                                   JNIEnv *env,
1899                                   jclass ofClass, jboolean publicOnly,
1900                                   bool want_constructor,
1901                                   Klass* klass, TRAPS) {
1902 
1903   JvmtiVMObjectAllocEventCollector oam;
1904 
1905   // Exclude primitive types and array types
1906   if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(ofClass))
1907       || java_lang_Class::as_Klass(JNIHandles::resolve_non_null(ofClass))->is_array_klass()) {
1908     // Return empty array
1909     oop res = oopFactory::new_objArray(klass, 0, CHECK_NULL);
1910     return (jobjectArray) JNIHandles::make_local(env, res);
1911   }
1912 
1913   InstanceKlass* k = InstanceKlass::cast(java_lang_Class::as_Klass(JNIHandles::resolve_non_null(ofClass)));
1914 
1915   // Ensure class is linked
1916   k->link_class(CHECK_NULL);
1917 
1918   Array<Method*>* methods = k->methods();
1919   int methods_length = methods->length();
1920 
1921   // Save original method_idnum in case of redefinition, which can change
1922   // the idnum of obsolete methods.  The new method will have the same idnum
1923   // but if we refresh the methods array, the counts will be wrong.
1924   ResourceMark rm(THREAD);
1925   GrowableArray<int>* idnums = new GrowableArray<int>(methods_length);
1926   int num_methods = 0;
1927 
1928   for (int i = 0; i < methods_length; i++) {
1929     methodHandle method(THREAD, methods->at(i));
1930     if (select_method(method, want_constructor)) {
1931       if (!publicOnly || method->is_public()) {
1932         idnums->push(method->method_idnum());
1933         ++num_methods;
1934       }
1935     }
1936   }
1937 
1938   // Allocate result
1939   objArrayOop r = oopFactory::new_objArray(klass, num_methods, CHECK_NULL);
1940   objArrayHandle result (THREAD, r);
1941 
1942   // Now just put the methods that we selected above, but go by their idnum
1943   // in case of redefinition.  The methods can be redefined at any safepoint,
1944   // so above when allocating the oop array and below when creating reflect
1945   // objects.
1946   for (int i = 0; i < num_methods; i++) {
1947     methodHandle method(THREAD, k->method_with_idnum(idnums->at(i)));
1948     if (method.is_null()) {
1949       // Method may have been deleted and seems this API can handle null
1950       // Otherwise should probably put a method that throws NSME
1951       result->obj_at_put(i, NULL);
1952     } else {
1953       oop m;
1954       if (want_constructor) {
1955         m = Reflection::new_constructor(method, CHECK_NULL);
1956       } else {
1957         m = Reflection::new_method(method, false, CHECK_NULL);
1958       }
1959       result->obj_at_put(i, m);
1960     }
1961   }
1962 
1963   return (jobjectArray) JNIHandles::make_local(env, result());
1964 }
1965 
1966 JVM_ENTRY(jobjectArray, JVM_GetClassDeclaredMethods(JNIEnv *env, jclass ofClass, jboolean publicOnly))
1967 {
1968   JVMWrapper("JVM_GetClassDeclaredMethods");
1969   return get_class_declared_methods_helper(env, ofClass, publicOnly,
1970                                            /*want_constructor*/ false,
1971                                            SystemDictionary::reflect_Method_klass(), THREAD);
1972 }
1973 JVM_END
1974 
1975 JVM_ENTRY(jobjectArray, JVM_GetClassDeclaredConstructors(JNIEnv *env, jclass ofClass, jboolean publicOnly))
1976 {
1977   JVMWrapper("JVM_GetClassDeclaredConstructors");
1978   return get_class_declared_methods_helper(env, ofClass, publicOnly,
1979                                            /*want_constructor*/ true,
1980                                            SystemDictionary::reflect_Constructor_klass(), THREAD);
1981 }
1982 JVM_END
1983 
1984 JVM_ENTRY(jint, JVM_GetClassAccessFlags(JNIEnv *env, jclass cls))
1985 {
1986   JVMWrapper("JVM_GetClassAccessFlags");
1987   if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(cls))) {
1988     // Primitive type
1989     return JVM_ACC_ABSTRACT | JVM_ACC_FINAL | JVM_ACC_PUBLIC;
1990   }
1991 
1992   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
1993   return k->access_flags().as_int() & JVM_ACC_WRITTEN_FLAGS;
1994 }
1995 JVM_END
1996 
1997 JVM_ENTRY(jboolean, JVM_AreNestMates(JNIEnv *env, jclass current, jclass member))
1998 {
1999   JVMWrapper("JVM_AreNestMates");
2000   Klass* c = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(current));
2001   assert(c->is_instance_klass(), "must be");
2002   InstanceKlass* ck = InstanceKlass::cast(c);
2003   Klass* m = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(member));
2004   assert(m->is_instance_klass(), "must be");
2005   InstanceKlass* mk = InstanceKlass::cast(m);
2006   return ck->has_nestmate_access_to(mk, THREAD);
2007 }
2008 JVM_END
2009 
2010 JVM_ENTRY(jclass, JVM_GetNestHost(JNIEnv* env, jclass current))
2011 {
2012   // current is not a primitive or array class
2013   JVMWrapper("JVM_GetNestHost");
2014   Klass* c = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(current));
2015   assert(c->is_instance_klass(), "must be");
2016   InstanceKlass* ck = InstanceKlass::cast(c);
2017   InstanceKlass* host = ck->nest_host(THREAD);
2018   return (jclass) (host == NULL ? NULL :
2019                    JNIHandles::make_local(THREAD, host->java_mirror()));
2020 }
2021 JVM_END
2022 
2023 JVM_ENTRY(jobjectArray, JVM_GetNestMembers(JNIEnv* env, jclass current))
2024 {
2025   // current is not a primitive or array class
2026   JVMWrapper("JVM_GetNestMembers");
2027   ResourceMark rm(THREAD);
2028   Klass* c = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(current));
2029   assert(c->is_instance_klass(), "must be");
2030   InstanceKlass* ck = InstanceKlass::cast(c);
2031   InstanceKlass* host = ck->nest_host(THREAD);
2032 
2033   log_trace(class, nestmates)("Calling GetNestMembers for type %s with nest-host %s",
2034                               ck->external_name(), host->external_name());
2035   {
2036     JvmtiVMObjectAllocEventCollector oam;
2037     Array<u2>* members = host->nest_members();
2038     int length = members == NULL ? 0 : members->length();
2039 
2040     log_trace(class, nestmates)(" - host has %d listed nest members", length);
2041 
2042     // nest host is first in the array so make it one bigger
2043     objArrayOop r = oopFactory::new_objArray(SystemDictionary::Class_klass(),
2044                                              length + 1, CHECK_NULL);
2045     objArrayHandle result(THREAD, r);
2046     result->obj_at_put(0, host->java_mirror());
2047     if (length != 0) {
2048       int count = 0;
2049       for (int i = 0; i < length; i++) {
2050         int cp_index = members->at(i);
2051         Klass* k = host->constants()->klass_at(cp_index, THREAD);
2052         if (HAS_PENDING_EXCEPTION) {
2053           if (PENDING_EXCEPTION->is_a(SystemDictionary::VirtualMachineError_klass())) {
2054             return NULL; // propagate VMEs
2055           }
2056           if (log_is_enabled(Trace, class, nestmates)) {
2057             stringStream ss;
2058             char* target_member_class = host->constants()->klass_name_at(cp_index)->as_C_string();
2059             ss.print(" - resolution of nest member %s failed: ", target_member_class);
2060             java_lang_Throwable::print(PENDING_EXCEPTION, &ss);
2061             log_trace(class, nestmates)("%s", ss.as_string());
2062           }
2063           CLEAR_PENDING_EXCEPTION;
2064           continue;
2065         }
2066         if (k->is_instance_klass()) {
2067           InstanceKlass* ik = InstanceKlass::cast(k);
2068           InstanceKlass* nest_host_k = ik->nest_host(CHECK_NULL);
2069           if (nest_host_k == host) {
2070             result->obj_at_put(count+1, k->java_mirror());
2071             count++;
2072             log_trace(class, nestmates)(" - [%d] = %s", count, ik->external_name());
2073           } else {
2074             log_trace(class, nestmates)(" - skipping member %s with different host %s",
2075                                         ik->external_name(), nest_host_k->external_name());
2076           }
2077         } else {
2078           log_trace(class, nestmates)(" - skipping member %s that is not an instance class",
2079                                       k->external_name());
2080         }
2081       }
2082       if (count < length) {
2083         // we had invalid entries so we need to compact the array
2084         log_trace(class, nestmates)(" - compacting array from length %d to %d",
2085                                     length + 1, count + 1);
2086 
2087         objArrayOop r2 = oopFactory::new_objArray(SystemDictionary::Class_klass(),
2088                                                   count + 1, CHECK_NULL);
2089         objArrayHandle result2(THREAD, r2);
2090         for (int i = 0; i < count + 1; i++) {
2091           result2->obj_at_put(i, result->obj_at(i));
2092         }
2093         return (jobjectArray)JNIHandles::make_local(THREAD, result2());
2094       }
2095     }
2096     else {
2097       assert(host == ck || ck->is_hidden(), "must be singleton nest or dynamic nestmate");
2098     }
2099     return (jobjectArray)JNIHandles::make_local(THREAD, result());
2100   }
2101 }
2102 JVM_END
2103 
2104 // Constant pool access //////////////////////////////////////////////////////////
2105 
2106 JVM_ENTRY(jobject, JVM_GetClassConstantPool(JNIEnv *env, jclass cls))
2107 {
2108   JVMWrapper("JVM_GetClassConstantPool");
2109   JvmtiVMObjectAllocEventCollector oam;
2110 
2111   // Return null for primitives and arrays
2112   if (!java_lang_Class::is_primitive(JNIHandles::resolve_non_null(cls))) {
2113     Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2114     if (k->is_instance_klass()) {
2115       InstanceKlass* k_h = InstanceKlass::cast(k);
2116       Handle jcp = reflect_ConstantPool::create(CHECK_NULL);
2117       reflect_ConstantPool::set_cp(jcp(), k_h->constants());
2118       return JNIHandles::make_local(jcp());
2119     }
2120   }
2121   return NULL;
2122 }
2123 JVM_END
2124 
2125 
2126 JVM_ENTRY(jint, JVM_ConstantPoolGetSize(JNIEnv *env, jobject obj, jobject unused))
2127 {
2128   JVMWrapper("JVM_ConstantPoolGetSize");
2129   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2130   return cp->length();
2131 }
2132 JVM_END
2133 
2134 
2135 JVM_ENTRY(jclass, JVM_ConstantPoolGetClassAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2136 {
2137   JVMWrapper("JVM_ConstantPoolGetClassAt");
2138   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2139   bounds_check(cp, index, CHECK_NULL);
2140   constantTag tag = cp->tag_at(index);
2141   if (!tag.is_klass() && !tag.is_unresolved_klass()) {
2142     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2143   }
2144   Klass* k = cp->klass_at(index, CHECK_NULL);
2145   return (jclass) JNIHandles::make_local(k->java_mirror());
2146 }
2147 JVM_END
2148 
2149 JVM_ENTRY(jclass, JVM_ConstantPoolGetClassAtIfLoaded(JNIEnv *env, jobject obj, jobject unused, jint index))
2150 {
2151   JVMWrapper("JVM_ConstantPoolGetClassAtIfLoaded");
2152   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2153   bounds_check(cp, index, CHECK_NULL);
2154   constantTag tag = cp->tag_at(index);
2155   if (!tag.is_klass() && !tag.is_unresolved_klass()) {
2156     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2157   }
2158   Klass* k = ConstantPool::klass_at_if_loaded(cp, index);
2159   if (k == NULL) return NULL;
2160   return (jclass) JNIHandles::make_local(k->java_mirror());
2161 }
2162 JVM_END
2163 
2164 static jobject get_method_at_helper(const constantPoolHandle& cp, jint index, bool force_resolution, TRAPS) {
2165   constantTag tag = cp->tag_at(index);
2166   if (!tag.is_method() && !tag.is_interface_method()) {
2167     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2168   }
2169   int klass_ref  = cp->uncached_klass_ref_index_at(index);
2170   Klass* k_o;
2171   if (force_resolution) {
2172     k_o = cp->klass_at(klass_ref, CHECK_NULL);
2173   } else {
2174     k_o = ConstantPool::klass_at_if_loaded(cp, klass_ref);
2175     if (k_o == NULL) return NULL;
2176   }
2177   InstanceKlass* k = InstanceKlass::cast(k_o);
2178   Symbol* name = cp->uncached_name_ref_at(index);
2179   Symbol* sig  = cp->uncached_signature_ref_at(index);
2180   methodHandle m (THREAD, k->find_method(name, sig));
2181   if (m.is_null()) {
2182     THROW_MSG_0(vmSymbols::java_lang_RuntimeException(), "Unable to look up method in target class");
2183   }
2184   oop method;
2185   if (!m->is_initializer() || m->is_static()) {
2186     method = Reflection::new_method(m, true, CHECK_NULL);
2187   } else {
2188     method = Reflection::new_constructor(m, CHECK_NULL);
2189   }
2190   return JNIHandles::make_local(method);
2191 }
2192 
2193 JVM_ENTRY(jobject, JVM_ConstantPoolGetMethodAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2194 {
2195   JVMWrapper("JVM_ConstantPoolGetMethodAt");
2196   JvmtiVMObjectAllocEventCollector oam;
2197   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2198   bounds_check(cp, index, CHECK_NULL);
2199   jobject res = get_method_at_helper(cp, index, true, CHECK_NULL);
2200   return res;
2201 }
2202 JVM_END
2203 
2204 JVM_ENTRY(jobject, JVM_ConstantPoolGetMethodAtIfLoaded(JNIEnv *env, jobject obj, jobject unused, jint index))
2205 {
2206   JVMWrapper("JVM_ConstantPoolGetMethodAtIfLoaded");
2207   JvmtiVMObjectAllocEventCollector oam;
2208   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2209   bounds_check(cp, index, CHECK_NULL);
2210   jobject res = get_method_at_helper(cp, index, false, CHECK_NULL);
2211   return res;
2212 }
2213 JVM_END
2214 
2215 static jobject get_field_at_helper(constantPoolHandle cp, jint index, bool force_resolution, TRAPS) {
2216   constantTag tag = cp->tag_at(index);
2217   if (!tag.is_field()) {
2218     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2219   }
2220   int klass_ref  = cp->uncached_klass_ref_index_at(index);
2221   Klass* k_o;
2222   if (force_resolution) {
2223     k_o = cp->klass_at(klass_ref, CHECK_NULL);
2224   } else {
2225     k_o = ConstantPool::klass_at_if_loaded(cp, klass_ref);
2226     if (k_o == NULL) return NULL;
2227   }
2228   InstanceKlass* k = InstanceKlass::cast(k_o);
2229   Symbol* name = cp->uncached_name_ref_at(index);
2230   Symbol* sig  = cp->uncached_signature_ref_at(index);
2231   fieldDescriptor fd;
2232   Klass* target_klass = k->find_field(name, sig, &fd);
2233   if (target_klass == NULL) {
2234     THROW_MSG_0(vmSymbols::java_lang_RuntimeException(), "Unable to look up field in target class");
2235   }
2236   oop field = Reflection::new_field(&fd, CHECK_NULL);
2237   return JNIHandles::make_local(field);
2238 }
2239 
2240 JVM_ENTRY(jobject, JVM_ConstantPoolGetFieldAt(JNIEnv *env, jobject obj, jobject unusedl, jint index))
2241 {
2242   JVMWrapper("JVM_ConstantPoolGetFieldAt");
2243   JvmtiVMObjectAllocEventCollector oam;
2244   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2245   bounds_check(cp, index, CHECK_NULL);
2246   jobject res = get_field_at_helper(cp, index, true, CHECK_NULL);
2247   return res;
2248 }
2249 JVM_END
2250 
2251 JVM_ENTRY(jobject, JVM_ConstantPoolGetFieldAtIfLoaded(JNIEnv *env, jobject obj, jobject unused, jint index))
2252 {
2253   JVMWrapper("JVM_ConstantPoolGetFieldAtIfLoaded");
2254   JvmtiVMObjectAllocEventCollector oam;
2255   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2256   bounds_check(cp, index, CHECK_NULL);
2257   jobject res = get_field_at_helper(cp, index, false, CHECK_NULL);
2258   return res;
2259 }
2260 JVM_END
2261 
2262 JVM_ENTRY(jobjectArray, JVM_ConstantPoolGetMemberRefInfoAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2263 {
2264   JVMWrapper("JVM_ConstantPoolGetMemberRefInfoAt");
2265   JvmtiVMObjectAllocEventCollector oam;
2266   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2267   bounds_check(cp, index, CHECK_NULL);
2268   constantTag tag = cp->tag_at(index);
2269   if (!tag.is_field_or_method()) {
2270     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2271   }
2272   int klass_ref = cp->uncached_klass_ref_index_at(index);
2273   Symbol*  klass_name  = cp->klass_name_at(klass_ref);
2274   Symbol*  member_name = cp->uncached_name_ref_at(index);
2275   Symbol*  member_sig  = cp->uncached_signature_ref_at(index);
2276   objArrayOop  dest_o = oopFactory::new_objArray(SystemDictionary::String_klass(), 3, CHECK_NULL);
2277   objArrayHandle dest(THREAD, dest_o);
2278   Handle str = java_lang_String::create_from_symbol(klass_name, CHECK_NULL);
2279   dest->obj_at_put(0, str());
2280   str = java_lang_String::create_from_symbol(member_name, CHECK_NULL);
2281   dest->obj_at_put(1, str());
2282   str = java_lang_String::create_from_symbol(member_sig, CHECK_NULL);
2283   dest->obj_at_put(2, str());
2284   return (jobjectArray) JNIHandles::make_local(dest());
2285 }
2286 JVM_END
2287 
2288 JVM_ENTRY(jint, JVM_ConstantPoolGetClassRefIndexAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2289 {
2290   JVMWrapper("JVM_ConstantPoolGetClassRefIndexAt");
2291   JvmtiVMObjectAllocEventCollector oam;
2292   constantPoolHandle cp(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2293   bounds_check(cp, index, CHECK_0);
2294   constantTag tag = cp->tag_at(index);
2295   if (!tag.is_field_or_method()) {
2296     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2297   }
2298   return (jint) cp->uncached_klass_ref_index_at(index);
2299 }
2300 JVM_END
2301 
2302 JVM_ENTRY(jint, JVM_ConstantPoolGetNameAndTypeRefIndexAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2303 {
2304   JVMWrapper("JVM_ConstantPoolGetNameAndTypeRefIndexAt");
2305   JvmtiVMObjectAllocEventCollector oam;
2306   constantPoolHandle cp(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2307   bounds_check(cp, index, CHECK_0);
2308   constantTag tag = cp->tag_at(index);
2309   if (!tag.is_invoke_dynamic() && !tag.is_field_or_method()) {
2310     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2311   }
2312   return (jint) cp->uncached_name_and_type_ref_index_at(index);
2313 }
2314 JVM_END
2315 
2316 JVM_ENTRY(jobjectArray, JVM_ConstantPoolGetNameAndTypeRefInfoAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2317 {
2318   JVMWrapper("JVM_ConstantPoolGetNameAndTypeRefInfoAt");
2319   JvmtiVMObjectAllocEventCollector oam;
2320   constantPoolHandle cp(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2321   bounds_check(cp, index, CHECK_NULL);
2322   constantTag tag = cp->tag_at(index);
2323   if (!tag.is_name_and_type()) {
2324     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2325   }
2326   Symbol* member_name = cp->symbol_at(cp->name_ref_index_at(index));
2327   Symbol* member_sig = cp->symbol_at(cp->signature_ref_index_at(index));
2328   objArrayOop dest_o = oopFactory::new_objArray(SystemDictionary::String_klass(), 2, CHECK_NULL);
2329   objArrayHandle dest(THREAD, dest_o);
2330   Handle str = java_lang_String::create_from_symbol(member_name, CHECK_NULL);
2331   dest->obj_at_put(0, str());
2332   str = java_lang_String::create_from_symbol(member_sig, CHECK_NULL);
2333   dest->obj_at_put(1, str());
2334   return (jobjectArray) JNIHandles::make_local(dest());
2335 }
2336 JVM_END
2337 
2338 JVM_ENTRY(jint, JVM_ConstantPoolGetIntAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2339 {
2340   JVMWrapper("JVM_ConstantPoolGetIntAt");
2341   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2342   bounds_check(cp, index, CHECK_0);
2343   constantTag tag = cp->tag_at(index);
2344   if (!tag.is_int()) {
2345     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2346   }
2347   return cp->int_at(index);
2348 }
2349 JVM_END
2350 
2351 JVM_ENTRY(jlong, JVM_ConstantPoolGetLongAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2352 {
2353   JVMWrapper("JVM_ConstantPoolGetLongAt");
2354   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2355   bounds_check(cp, index, CHECK_(0L));
2356   constantTag tag = cp->tag_at(index);
2357   if (!tag.is_long()) {
2358     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2359   }
2360   return cp->long_at(index);
2361 }
2362 JVM_END
2363 
2364 JVM_ENTRY(jfloat, JVM_ConstantPoolGetFloatAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2365 {
2366   JVMWrapper("JVM_ConstantPoolGetFloatAt");
2367   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2368   bounds_check(cp, index, CHECK_(0.0f));
2369   constantTag tag = cp->tag_at(index);
2370   if (!tag.is_float()) {
2371     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2372   }
2373   return cp->float_at(index);
2374 }
2375 JVM_END
2376 
2377 JVM_ENTRY(jdouble, JVM_ConstantPoolGetDoubleAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2378 {
2379   JVMWrapper("JVM_ConstantPoolGetDoubleAt");
2380   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2381   bounds_check(cp, index, CHECK_(0.0));
2382   constantTag tag = cp->tag_at(index);
2383   if (!tag.is_double()) {
2384     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2385   }
2386   return cp->double_at(index);
2387 }
2388 JVM_END
2389 
2390 JVM_ENTRY(jstring, JVM_ConstantPoolGetStringAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2391 {
2392   JVMWrapper("JVM_ConstantPoolGetStringAt");
2393   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2394   bounds_check(cp, index, CHECK_NULL);
2395   constantTag tag = cp->tag_at(index);
2396   if (!tag.is_string()) {
2397     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2398   }
2399   oop str = cp->string_at(index, CHECK_NULL);
2400   return (jstring) JNIHandles::make_local(str);
2401 }
2402 JVM_END
2403 
2404 JVM_ENTRY(jstring, JVM_ConstantPoolGetUTF8At(JNIEnv *env, jobject obj, jobject unused, jint index))
2405 {
2406   JVMWrapper("JVM_ConstantPoolGetUTF8At");
2407   JvmtiVMObjectAllocEventCollector oam;
2408   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2409   bounds_check(cp, index, CHECK_NULL);
2410   constantTag tag = cp->tag_at(index);
2411   if (!tag.is_symbol()) {
2412     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2413   }
2414   Symbol* sym = cp->symbol_at(index);
2415   Handle str = java_lang_String::create_from_symbol(sym, CHECK_NULL);
2416   return (jstring) JNIHandles::make_local(str());
2417 }
2418 JVM_END
2419 
2420 JVM_ENTRY(jbyte, JVM_ConstantPoolGetTagAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2421 {
2422   JVMWrapper("JVM_ConstantPoolGetTagAt");
2423   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2424   bounds_check(cp, index, CHECK_0);
2425   constantTag tag = cp->tag_at(index);
2426   jbyte result = tag.value();
2427   // If returned tag values are not from the JVM spec, e.g. tags from 100 to 105,
2428   // they are changed to the corresponding tags from the JVM spec, so that java code in
2429   // sun.reflect.ConstantPool will return only tags from the JVM spec, not internal ones.
2430   if (tag.is_klass_or_reference()) {
2431       result = JVM_CONSTANT_Class;
2432   } else if (tag.is_string_index()) {
2433       result = JVM_CONSTANT_String;
2434   } else if (tag.is_method_type_in_error()) {
2435       result = JVM_CONSTANT_MethodType;
2436   } else if (tag.is_method_handle_in_error()) {
2437       result = JVM_CONSTANT_MethodHandle;
2438   } else if (tag.is_dynamic_constant_in_error()) {
2439       result = JVM_CONSTANT_Dynamic;
2440   }
2441   return result;
2442 }
2443 JVM_END
2444 
2445 // Assertion support. //////////////////////////////////////////////////////////
2446 
2447 JVM_ENTRY(jboolean, JVM_DesiredAssertionStatus(JNIEnv *env, jclass unused, jclass cls))
2448   JVMWrapper("JVM_DesiredAssertionStatus");
2449   assert(cls != NULL, "bad class");
2450 
2451   oop r = JNIHandles::resolve(cls);
2452   assert(! java_lang_Class::is_primitive(r), "primitive classes not allowed");
2453   if (java_lang_Class::is_primitive(r)) return false;
2454 
2455   Klass* k = java_lang_Class::as_Klass(r);
2456   assert(k->is_instance_klass(), "must be an instance klass");
2457   if (!k->is_instance_klass()) return false;
2458 
2459   ResourceMark rm(THREAD);
2460   const char* name = k->name()->as_C_string();
2461   bool system_class = k->class_loader() == NULL;
2462   return JavaAssertions::enabled(name, system_class);
2463 
2464 JVM_END
2465 
2466 
2467 // Return a new AssertionStatusDirectives object with the fields filled in with
2468 // command-line assertion arguments (i.e., -ea, -da).
2469 JVM_ENTRY(jobject, JVM_AssertionStatusDirectives(JNIEnv *env, jclass unused))
2470   JVMWrapper("JVM_AssertionStatusDirectives");
2471   JvmtiVMObjectAllocEventCollector oam;
2472   oop asd = JavaAssertions::createAssertionStatusDirectives(CHECK_NULL);
2473   return JNIHandles::make_local(env, asd);
2474 JVM_END
2475 
2476 // Verification ////////////////////////////////////////////////////////////////////////////////
2477 
2478 // Reflection for the verifier /////////////////////////////////////////////////////////////////
2479 
2480 // RedefineClasses support: bug 6214132 caused verification to fail.
2481 // All functions from this section should call the jvmtiThreadSate function:
2482 //   Klass* class_to_verify_considering_redefinition(Klass* klass).
2483 // The function returns a Klass* of the _scratch_class if the verifier
2484 // was invoked in the middle of the class redefinition.
2485 // Otherwise it returns its argument value which is the _the_class Klass*.
2486 // Please, refer to the description in the jvmtiThreadSate.hpp.
2487 
2488 JVM_ENTRY(const char*, JVM_GetClassNameUTF(JNIEnv *env, jclass cls))
2489   JVMWrapper("JVM_GetClassNameUTF");
2490   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2491   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2492   return k->name()->as_utf8();
2493 JVM_END
2494 
2495 
2496 JVM_ENTRY(void, JVM_GetClassCPTypes(JNIEnv *env, jclass cls, unsigned char *types))
2497   JVMWrapper("JVM_GetClassCPTypes");
2498   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2499   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2500   // types will have length zero if this is not an InstanceKlass
2501   // (length is determined by call to JVM_GetClassCPEntriesCount)
2502   if (k->is_instance_klass()) {
2503     ConstantPool* cp = InstanceKlass::cast(k)->constants();
2504     for (int index = cp->length() - 1; index >= 0; index--) {
2505       constantTag tag = cp->tag_at(index);
2506       types[index] = (tag.is_unresolved_klass()) ? (unsigned char) JVM_CONSTANT_Class : tag.value();
2507     }
2508   }
2509 JVM_END
2510 
2511 
2512 JVM_ENTRY(jint, JVM_GetClassCPEntriesCount(JNIEnv *env, jclass cls))
2513   JVMWrapper("JVM_GetClassCPEntriesCount");
2514   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2515   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2516   return (!k->is_instance_klass()) ? 0 : InstanceKlass::cast(k)->constants()->length();
2517 JVM_END
2518 
2519 
2520 JVM_ENTRY(jint, JVM_GetClassFieldsCount(JNIEnv *env, jclass cls))
2521   JVMWrapper("JVM_GetClassFieldsCount");
2522   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2523   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2524   return (!k->is_instance_klass()) ? 0 : InstanceKlass::cast(k)->java_fields_count();
2525 JVM_END
2526 
2527 
2528 JVM_ENTRY(jint, JVM_GetClassMethodsCount(JNIEnv *env, jclass cls))
2529   JVMWrapper("JVM_GetClassMethodsCount");
2530   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2531   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2532   return (!k->is_instance_klass()) ? 0 : InstanceKlass::cast(k)->methods()->length();
2533 JVM_END
2534 
2535 
2536 // The following methods, used for the verifier, are never called with
2537 // array klasses, so a direct cast to InstanceKlass is safe.
2538 // Typically, these methods are called in a loop with bounds determined
2539 // by the results of JVM_GetClass{Fields,Methods}Count, which return
2540 // zero for arrays.
2541 JVM_ENTRY(void, JVM_GetMethodIxExceptionIndexes(JNIEnv *env, jclass cls, jint method_index, unsigned short *exceptions))
2542   JVMWrapper("JVM_GetMethodIxExceptionIndexes");
2543   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2544   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2545   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2546   int length = method->checked_exceptions_length();
2547   if (length > 0) {
2548     CheckedExceptionElement* table= method->checked_exceptions_start();
2549     for (int i = 0; i < length; i++) {
2550       exceptions[i] = table[i].class_cp_index;
2551     }
2552   }
2553 JVM_END
2554 
2555 
2556 JVM_ENTRY(jint, JVM_GetMethodIxExceptionsCount(JNIEnv *env, jclass cls, jint method_index))
2557   JVMWrapper("JVM_GetMethodIxExceptionsCount");
2558   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2559   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2560   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2561   return method->checked_exceptions_length();
2562 JVM_END
2563 
2564 
2565 JVM_ENTRY(void, JVM_GetMethodIxByteCode(JNIEnv *env, jclass cls, jint method_index, unsigned char *code))
2566   JVMWrapper("JVM_GetMethodIxByteCode");
2567   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2568   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2569   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2570   memcpy(code, method->code_base(), method->code_size());
2571 JVM_END
2572 
2573 
2574 JVM_ENTRY(jint, JVM_GetMethodIxByteCodeLength(JNIEnv *env, jclass cls, jint method_index))
2575   JVMWrapper("JVM_GetMethodIxByteCodeLength");
2576   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2577   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2578   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2579   return method->code_size();
2580 JVM_END
2581 
2582 
2583 JVM_ENTRY(void, JVM_GetMethodIxExceptionTableEntry(JNIEnv *env, jclass cls, jint method_index, jint entry_index, JVM_ExceptionTableEntryType *entry))
2584   JVMWrapper("JVM_GetMethodIxExceptionTableEntry");
2585   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2586   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2587   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2588   ExceptionTable extable(method);
2589   entry->start_pc   = extable.start_pc(entry_index);
2590   entry->end_pc     = extable.end_pc(entry_index);
2591   entry->handler_pc = extable.handler_pc(entry_index);
2592   entry->catchType  = extable.catch_type_index(entry_index);
2593 JVM_END
2594 
2595 
2596 JVM_ENTRY(jint, JVM_GetMethodIxExceptionTableLength(JNIEnv *env, jclass cls, int method_index))
2597   JVMWrapper("JVM_GetMethodIxExceptionTableLength");
2598   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2599   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2600   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2601   return method->exception_table_length();
2602 JVM_END
2603 
2604 
2605 JVM_ENTRY(jint, JVM_GetMethodIxModifiers(JNIEnv *env, jclass cls, int method_index))
2606   JVMWrapper("JVM_GetMethodIxModifiers");
2607   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2608   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2609   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2610   return method->access_flags().as_int() & JVM_RECOGNIZED_METHOD_MODIFIERS;
2611 JVM_END
2612 
2613 
2614 JVM_ENTRY(jint, JVM_GetFieldIxModifiers(JNIEnv *env, jclass cls, int field_index))
2615   JVMWrapper("JVM_GetFieldIxModifiers");
2616   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2617   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2618   return InstanceKlass::cast(k)->field_access_flags(field_index) & JVM_RECOGNIZED_FIELD_MODIFIERS;
2619 JVM_END
2620 
2621 
2622 JVM_ENTRY(jint, JVM_GetMethodIxLocalsCount(JNIEnv *env, jclass cls, int method_index))
2623   JVMWrapper("JVM_GetMethodIxLocalsCount");
2624   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2625   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2626   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2627   return method->max_locals();
2628 JVM_END
2629 
2630 
2631 JVM_ENTRY(jint, JVM_GetMethodIxArgsSize(JNIEnv *env, jclass cls, int method_index))
2632   JVMWrapper("JVM_GetMethodIxArgsSize");
2633   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2634   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2635   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2636   return method->size_of_parameters();
2637 JVM_END
2638 
2639 
2640 JVM_ENTRY(jint, JVM_GetMethodIxMaxStack(JNIEnv *env, jclass cls, int method_index))
2641   JVMWrapper("JVM_GetMethodIxMaxStack");
2642   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2643   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2644   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2645   return method->verifier_max_stack();
2646 JVM_END
2647 
2648 
2649 JVM_ENTRY(jboolean, JVM_IsConstructorIx(JNIEnv *env, jclass cls, int method_index))
2650   JVMWrapper("JVM_IsConstructorIx");
2651   ResourceMark rm(THREAD);
2652   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2653   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2654   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2655   return method->name() == vmSymbols::object_initializer_name();
2656 JVM_END
2657 
2658 
2659 JVM_ENTRY(jboolean, JVM_IsVMGeneratedMethodIx(JNIEnv *env, jclass cls, int method_index))
2660   JVMWrapper("JVM_IsVMGeneratedMethodIx");
2661   ResourceMark rm(THREAD);
2662   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2663   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2664   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2665   return method->is_overpass();
2666 JVM_END
2667 
2668 JVM_ENTRY(const char*, JVM_GetMethodIxNameUTF(JNIEnv *env, jclass cls, jint method_index))
2669   JVMWrapper("JVM_GetMethodIxIxUTF");
2670   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2671   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2672   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2673   return method->name()->as_utf8();
2674 JVM_END
2675 
2676 
2677 JVM_ENTRY(const char*, JVM_GetMethodIxSignatureUTF(JNIEnv *env, jclass cls, jint method_index))
2678   JVMWrapper("JVM_GetMethodIxSignatureUTF");
2679   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2680   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2681   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2682   return method->signature()->as_utf8();
2683 JVM_END
2684 
2685 /**
2686  * All of these JVM_GetCP-xxx methods are used by the old verifier to
2687  * read entries in the constant pool.  Since the old verifier always
2688  * works on a copy of the code, it will not see any rewriting that
2689  * may possibly occur in the middle of verification.  So it is important
2690  * that nothing it calls tries to use the cpCache instead of the raw
2691  * constant pool, so we must use cp->uncached_x methods when appropriate.
2692  */
2693 JVM_ENTRY(const char*, JVM_GetCPFieldNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2694   JVMWrapper("JVM_GetCPFieldNameUTF");
2695   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2696   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2697   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2698   switch (cp->tag_at(cp_index).value()) {
2699     case JVM_CONSTANT_Fieldref:
2700       return cp->uncached_name_ref_at(cp_index)->as_utf8();
2701     default:
2702       fatal("JVM_GetCPFieldNameUTF: illegal constant");
2703   }
2704   ShouldNotReachHere();
2705   return NULL;
2706 JVM_END
2707 
2708 
2709 JVM_ENTRY(const char*, JVM_GetCPMethodNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2710   JVMWrapper("JVM_GetCPMethodNameUTF");
2711   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2712   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2713   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2714   switch (cp->tag_at(cp_index).value()) {
2715     case JVM_CONSTANT_InterfaceMethodref:
2716     case JVM_CONSTANT_Methodref:
2717       return cp->uncached_name_ref_at(cp_index)->as_utf8();
2718     default:
2719       fatal("JVM_GetCPMethodNameUTF: illegal constant");
2720   }
2721   ShouldNotReachHere();
2722   return NULL;
2723 JVM_END
2724 
2725 
2726 JVM_ENTRY(const char*, JVM_GetCPMethodSignatureUTF(JNIEnv *env, jclass cls, jint cp_index))
2727   JVMWrapper("JVM_GetCPMethodSignatureUTF");
2728   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2729   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2730   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2731   switch (cp->tag_at(cp_index).value()) {
2732     case JVM_CONSTANT_InterfaceMethodref:
2733     case JVM_CONSTANT_Methodref:
2734       return cp->uncached_signature_ref_at(cp_index)->as_utf8();
2735     default:
2736       fatal("JVM_GetCPMethodSignatureUTF: illegal constant");
2737   }
2738   ShouldNotReachHere();
2739   return NULL;
2740 JVM_END
2741 
2742 
2743 JVM_ENTRY(const char*, JVM_GetCPFieldSignatureUTF(JNIEnv *env, jclass cls, jint cp_index))
2744   JVMWrapper("JVM_GetCPFieldSignatureUTF");
2745   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2746   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2747   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2748   switch (cp->tag_at(cp_index).value()) {
2749     case JVM_CONSTANT_Fieldref:
2750       return cp->uncached_signature_ref_at(cp_index)->as_utf8();
2751     default:
2752       fatal("JVM_GetCPFieldSignatureUTF: illegal constant");
2753   }
2754   ShouldNotReachHere();
2755   return NULL;
2756 JVM_END
2757 
2758 
2759 JVM_ENTRY(const char*, JVM_GetCPClassNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2760   JVMWrapper("JVM_GetCPClassNameUTF");
2761   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2762   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2763   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2764   Symbol* classname = cp->klass_name_at(cp_index);
2765   return classname->as_utf8();
2766 JVM_END
2767 
2768 
2769 JVM_ENTRY(const char*, JVM_GetCPFieldClassNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2770   JVMWrapper("JVM_GetCPFieldClassNameUTF");
2771   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2772   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2773   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2774   switch (cp->tag_at(cp_index).value()) {
2775     case JVM_CONSTANT_Fieldref: {
2776       int class_index = cp->uncached_klass_ref_index_at(cp_index);
2777       Symbol* classname = cp->klass_name_at(class_index);
2778       return classname->as_utf8();
2779     }
2780     default:
2781       fatal("JVM_GetCPFieldClassNameUTF: illegal constant");
2782   }
2783   ShouldNotReachHere();
2784   return NULL;
2785 JVM_END
2786 
2787 
2788 JVM_ENTRY(const char*, JVM_GetCPMethodClassNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2789   JVMWrapper("JVM_GetCPMethodClassNameUTF");
2790   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2791   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2792   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2793   switch (cp->tag_at(cp_index).value()) {
2794     case JVM_CONSTANT_Methodref:
2795     case JVM_CONSTANT_InterfaceMethodref: {
2796       int class_index = cp->uncached_klass_ref_index_at(cp_index);
2797       Symbol* classname = cp->klass_name_at(class_index);
2798       return classname->as_utf8();
2799     }
2800     default:
2801       fatal("JVM_GetCPMethodClassNameUTF: illegal constant");
2802   }
2803   ShouldNotReachHere();
2804   return NULL;
2805 JVM_END
2806 
2807 
2808 JVM_ENTRY(jint, JVM_GetCPFieldModifiers(JNIEnv *env, jclass cls, int cp_index, jclass called_cls))
2809   JVMWrapper("JVM_GetCPFieldModifiers");
2810   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2811   Klass* k_called = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(called_cls));
2812   k        = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2813   k_called = JvmtiThreadState::class_to_verify_considering_redefinition(k_called, thread);
2814   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2815   ConstantPool* cp_called = InstanceKlass::cast(k_called)->constants();
2816   switch (cp->tag_at(cp_index).value()) {
2817     case JVM_CONSTANT_Fieldref: {
2818       Symbol* name      = cp->uncached_name_ref_at(cp_index);
2819       Symbol* signature = cp->uncached_signature_ref_at(cp_index);
2820       InstanceKlass* ik = InstanceKlass::cast(k_called);
2821       for (JavaFieldStream fs(ik); !fs.done(); fs.next()) {
2822         if (fs.name() == name && fs.signature() == signature) {
2823           return fs.access_flags().as_short() & JVM_RECOGNIZED_FIELD_MODIFIERS;
2824         }
2825       }
2826       return -1;
2827     }
2828     default:
2829       fatal("JVM_GetCPFieldModifiers: illegal constant");
2830   }
2831   ShouldNotReachHere();
2832   return 0;
2833 JVM_END
2834 
2835 
2836 JVM_ENTRY(jint, JVM_GetCPMethodModifiers(JNIEnv *env, jclass cls, int cp_index, jclass called_cls))
2837   JVMWrapper("JVM_GetCPMethodModifiers");
2838   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2839   Klass* k_called = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(called_cls));
2840   k        = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2841   k_called = JvmtiThreadState::class_to_verify_considering_redefinition(k_called, thread);
2842   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2843   switch (cp->tag_at(cp_index).value()) {
2844     case JVM_CONSTANT_Methodref:
2845     case JVM_CONSTANT_InterfaceMethodref: {
2846       Symbol* name      = cp->uncached_name_ref_at(cp_index);
2847       Symbol* signature = cp->uncached_signature_ref_at(cp_index);
2848       Array<Method*>* methods = InstanceKlass::cast(k_called)->methods();
2849       int methods_count = methods->length();
2850       for (int i = 0; i < methods_count; i++) {
2851         Method* method = methods->at(i);
2852         if (method->name() == name && method->signature() == signature) {
2853             return method->access_flags().as_int() & JVM_RECOGNIZED_METHOD_MODIFIERS;
2854         }
2855       }
2856       return -1;
2857     }
2858     default:
2859       fatal("JVM_GetCPMethodModifiers: illegal constant");
2860   }
2861   ShouldNotReachHere();
2862   return 0;
2863 JVM_END
2864 
2865 
2866 // Misc //////////////////////////////////////////////////////////////////////////////////////////////
2867 
2868 JVM_LEAF(void, JVM_ReleaseUTF(const char *utf))
2869   // So long as UTF8::convert_to_utf8 returns resource strings, we don't have to do anything
2870 JVM_END
2871 
2872 
2873 JVM_ENTRY(jboolean, JVM_IsSameClassPackage(JNIEnv *env, jclass class1, jclass class2))
2874   JVMWrapper("JVM_IsSameClassPackage");
2875   oop class1_mirror = JNIHandles::resolve_non_null(class1);
2876   oop class2_mirror = JNIHandles::resolve_non_null(class2);
2877   Klass* klass1 = java_lang_Class::as_Klass(class1_mirror);
2878   Klass* klass2 = java_lang_Class::as_Klass(class2_mirror);
2879   return (jboolean) Reflection::is_same_class_package(klass1, klass2);
2880 JVM_END
2881 
2882 // Printing support //////////////////////////////////////////////////
2883 extern "C" {
2884 
2885 ATTRIBUTE_PRINTF(3, 0)
2886 int jio_vsnprintf(char *str, size_t count, const char *fmt, va_list args) {
2887   // Reject count values that are negative signed values converted to
2888   // unsigned; see bug 4399518, 4417214
2889   if ((intptr_t)count <= 0) return -1;
2890 
2891   int result = os::vsnprintf(str, count, fmt, args);
2892   if (result > 0 && (size_t)result >= count) {
2893     result = -1;
2894   }
2895 
2896   return result;
2897 }
2898 
2899 ATTRIBUTE_PRINTF(3, 4)
2900 int jio_snprintf(char *str, size_t count, const char *fmt, ...) {
2901   va_list args;
2902   int len;
2903   va_start(args, fmt);
2904   len = jio_vsnprintf(str, count, fmt, args);
2905   va_end(args);
2906   return len;
2907 }
2908 
2909 ATTRIBUTE_PRINTF(2, 3)
2910 int jio_fprintf(FILE* f, const char *fmt, ...) {
2911   int len;
2912   va_list args;
2913   va_start(args, fmt);
2914   len = jio_vfprintf(f, fmt, args);
2915   va_end(args);
2916   return len;
2917 }
2918 
2919 ATTRIBUTE_PRINTF(2, 0)
2920 int jio_vfprintf(FILE* f, const char *fmt, va_list args) {
2921   if (Arguments::vfprintf_hook() != NULL) {
2922      return Arguments::vfprintf_hook()(f, fmt, args);
2923   } else {
2924     return vfprintf(f, fmt, args);
2925   }
2926 }
2927 
2928 ATTRIBUTE_PRINTF(1, 2)
2929 JNIEXPORT int jio_printf(const char *fmt, ...) {
2930   int len;
2931   va_list args;
2932   va_start(args, fmt);
2933   len = jio_vfprintf(defaultStream::output_stream(), fmt, args);
2934   va_end(args);
2935   return len;
2936 }
2937 
2938 // HotSpot specific jio method
2939 void jio_print(const char* s, size_t len) {
2940   // Try to make this function as atomic as possible.
2941   if (Arguments::vfprintf_hook() != NULL) {
2942     jio_fprintf(defaultStream::output_stream(), "%.*s", (int)len, s);
2943   } else {
2944     // Make an unused local variable to avoid warning from gcc compiler.
2945     size_t count = ::write(defaultStream::output_fd(), s, (int)len);
2946   }
2947 }
2948 
2949 } // Extern C
2950 
2951 // java.lang.Thread //////////////////////////////////////////////////////////////////////////////
2952 
2953 // In most of the JVM thread support functions we need to access the
2954 // thread through a ThreadsListHandle to prevent it from exiting and
2955 // being reclaimed while we try to operate on it. The exceptions to this
2956 // rule are when operating on the current thread, or if the monitor of
2957 // the target java.lang.Thread is locked at the Java level - in both
2958 // cases the target cannot exit.
2959 
2960 static void thread_entry(JavaThread* thread, TRAPS) {
2961   HandleMark hm(THREAD);
2962   Handle obj(THREAD, thread->threadObj());
2963   JavaValue result(T_VOID);
2964   JavaCalls::call_virtual(&result,
2965                           obj,
2966                           SystemDictionary::Thread_klass(),
2967                           vmSymbols::run_method_name(),
2968                           vmSymbols::void_method_signature(),
2969                           THREAD);
2970 }
2971 
2972 
2973 JVM_ENTRY(void, JVM_StartThread(JNIEnv* env, jobject jthread))
2974   JVMWrapper("JVM_StartThread");
2975   JavaThread *native_thread = NULL;
2976 
2977   // We cannot hold the Threads_lock when we throw an exception,
2978   // due to rank ordering issues. Example:  we might need to grab the
2979   // Heap_lock while we construct the exception.
2980   bool throw_illegal_thread_state = false;
2981 
2982   // We must release the Threads_lock before we can post a jvmti event
2983   // in Thread::start.
2984   {
2985     // Ensure that the C++ Thread and OSThread structures aren't freed before
2986     // we operate.
2987     MutexLocker mu(Threads_lock);
2988 
2989     // Since JDK 5 the java.lang.Thread threadStatus is used to prevent
2990     // re-starting an already started thread, so we should usually find
2991     // that the JavaThread is null. However for a JNI attached thread
2992     // there is a small window between the Thread object being created
2993     // (with its JavaThread set) and the update to its threadStatus, so we
2994     // have to check for this
2995     if (java_lang_Thread::thread(JNIHandles::resolve_non_null(jthread)) != NULL) {
2996       throw_illegal_thread_state = true;
2997     } else {
2998       // We could also check the stillborn flag to see if this thread was already stopped, but
2999       // for historical reasons we let the thread detect that itself when it starts running
3000 
3001       jlong size =
3002              java_lang_Thread::stackSize(JNIHandles::resolve_non_null(jthread));
3003       // Allocate the C++ Thread structure and create the native thread.  The
3004       // stack size retrieved from java is 64-bit signed, but the constructor takes
3005       // size_t (an unsigned type), which may be 32 or 64-bit depending on the platform.
3006       //  - Avoid truncating on 32-bit platforms if size is greater than UINT_MAX.
3007       //  - Avoid passing negative values which would result in really large stacks.
3008       NOT_LP64(if (size > SIZE_MAX) size = SIZE_MAX;)
3009       size_t sz = size > 0 ? (size_t) size : 0;
3010       native_thread = new JavaThread(&thread_entry, sz);
3011 
3012       // At this point it may be possible that no osthread was created for the
3013       // JavaThread due to lack of memory. Check for this situation and throw
3014       // an exception if necessary. Eventually we may want to change this so
3015       // that we only grab the lock if the thread was created successfully -
3016       // then we can also do this check and throw the exception in the
3017       // JavaThread constructor.
3018       if (native_thread->osthread() != NULL) {
3019         // Note: the current thread is not being used within "prepare".
3020         native_thread->prepare(jthread);
3021       }
3022     }
3023   }
3024 
3025   if (throw_illegal_thread_state) {
3026     THROW(vmSymbols::java_lang_IllegalThreadStateException());
3027   }
3028 
3029   assert(native_thread != NULL, "Starting null thread?");
3030 
3031   if (native_thread->osthread() == NULL) {
3032     // No one should hold a reference to the 'native_thread'.
3033     native_thread->smr_delete();
3034     if (JvmtiExport::should_post_resource_exhausted()) {
3035       JvmtiExport::post_resource_exhausted(
3036         JVMTI_RESOURCE_EXHAUSTED_OOM_ERROR | JVMTI_RESOURCE_EXHAUSTED_THREADS,
3037         os::native_thread_creation_failed_msg());
3038     }
3039     THROW_MSG(vmSymbols::java_lang_OutOfMemoryError(),
3040               os::native_thread_creation_failed_msg());
3041   }
3042 
3043 #if INCLUDE_JFR
3044   if (JfrRecorder::is_recording() && EventThreadStart::is_enabled() &&
3045       EventThreadStart::is_stacktrace_enabled()) {
3046     JfrThreadLocal* tl = native_thread->jfr_thread_local();
3047     // skip Thread.start() and Thread.start0()
3048     tl->set_cached_stack_trace_id(JfrStackTraceRepository::record(thread, 2));
3049   }
3050 #endif
3051 
3052   Thread::start(native_thread);
3053 
3054 JVM_END
3055 
3056 
3057 // JVM_Stop is implemented using a VM_Operation, so threads are forced to safepoints
3058 // before the quasi-asynchronous exception is delivered.  This is a little obtrusive,
3059 // but is thought to be reliable and simple. In the case, where the receiver is the
3060 // same thread as the sender, no VM_Operation is needed.
3061 JVM_ENTRY(void, JVM_StopThread(JNIEnv* env, jobject jthread, jobject throwable))
3062   JVMWrapper("JVM_StopThread");
3063 
3064   // A nested ThreadsListHandle will grab the Threads_lock so create
3065   // tlh before we resolve throwable.
3066   ThreadsListHandle tlh(thread);
3067   oop java_throwable = JNIHandles::resolve(throwable);
3068   if (java_throwable == NULL) {
3069     THROW(vmSymbols::java_lang_NullPointerException());
3070   }
3071   oop java_thread = NULL;
3072   JavaThread* receiver = NULL;
3073   bool is_alive = tlh.cv_internal_thread_to_JavaThread(jthread, &receiver, &java_thread);
3074   Events::log_exception(thread,
3075                         "JVM_StopThread thread JavaThread " INTPTR_FORMAT " as oop " INTPTR_FORMAT " [exception " INTPTR_FORMAT "]",
3076                         p2i(receiver), p2i(java_thread), p2i(throwable));
3077 
3078   if (is_alive) {
3079     // jthread refers to a live JavaThread.
3080     if (thread == receiver) {
3081       // Exception is getting thrown at self so no VM_Operation needed.
3082       THROW_OOP(java_throwable);
3083     } else {
3084       // Use a VM_Operation to throw the exception.
3085       Thread::send_async_exception(java_thread, java_throwable);
3086     }
3087   } else {
3088     // Either:
3089     // - target thread has not been started before being stopped, or
3090     // - target thread already terminated
3091     // We could read the threadStatus to determine which case it is
3092     // but that is overkill as it doesn't matter. We must set the
3093     // stillborn flag for the first case, and if the thread has already
3094     // exited setting this flag has no effect.
3095     java_lang_Thread::set_stillborn(java_thread);
3096   }
3097 JVM_END
3098 
3099 
3100 JVM_ENTRY(jboolean, JVM_IsThreadAlive(JNIEnv* env, jobject jthread))
3101   JVMWrapper("JVM_IsThreadAlive");
3102 
3103   oop thread_oop = JNIHandles::resolve_non_null(jthread);
3104   return java_lang_Thread::is_alive(thread_oop);
3105 JVM_END
3106 
3107 
3108 JVM_ENTRY(void, JVM_SuspendThread(JNIEnv* env, jobject jthread))
3109   JVMWrapper("JVM_SuspendThread");
3110 
3111   ThreadsListHandle tlh(thread);
3112   JavaThread* receiver = NULL;
3113   bool is_alive = tlh.cv_internal_thread_to_JavaThread(jthread, &receiver, NULL);
3114   if (is_alive) {
3115     // jthread refers to a live JavaThread.
3116     {
3117       MutexLocker ml(receiver->SR_lock(), Mutex::_no_safepoint_check_flag);
3118       if (receiver->is_external_suspend()) {
3119         // Don't allow nested external suspend requests. We can't return
3120         // an error from this interface so just ignore the problem.
3121         return;
3122       }
3123       if (receiver->is_exiting()) { // thread is in the process of exiting
3124         return;
3125       }
3126       receiver->set_external_suspend();
3127     }
3128 
3129     // java_suspend() will catch threads in the process of exiting
3130     // and will ignore them.
3131     receiver->java_suspend();
3132 
3133     // It would be nice to have the following assertion in all the
3134     // time, but it is possible for a racing resume request to have
3135     // resumed this thread right after we suspended it. Temporarily
3136     // enable this assertion if you are chasing a different kind of
3137     // bug.
3138     //
3139     // assert(java_lang_Thread::thread(receiver->threadObj()) == NULL ||
3140     //   receiver->is_being_ext_suspended(), "thread is not suspended");
3141   }
3142 JVM_END
3143 
3144 
3145 JVM_ENTRY(void, JVM_ResumeThread(JNIEnv* env, jobject jthread))
3146   JVMWrapper("JVM_ResumeThread");
3147 
3148   ThreadsListHandle tlh(thread);
3149   JavaThread* receiver = NULL;
3150   bool is_alive = tlh.cv_internal_thread_to_JavaThread(jthread, &receiver, NULL);
3151   if (is_alive) {
3152     // jthread refers to a live JavaThread.
3153 
3154     // This is the original comment for this Threads_lock grab:
3155     //   We need to *always* get the threads lock here, since this operation cannot be allowed during
3156     //   a safepoint. The safepoint code relies on suspending a thread to examine its state. If other
3157     //   threads randomly resumes threads, then a thread might not be suspended when the safepoint code
3158     //   looks at it.
3159     //
3160     // The above comment dates back to when we had both internal and
3161     // external suspend APIs that shared a common underlying mechanism.
3162     // External suspend is now entirely cooperative and doesn't share
3163     // anything with internal suspend. That said, there are some
3164     // assumptions in the VM that an external resume grabs the
3165     // Threads_lock. We can't drop the Threads_lock grab here until we
3166     // resolve the assumptions that exist elsewhere.
3167     //
3168     MutexLocker ml(Threads_lock);
3169     receiver->java_resume();
3170   }
3171 JVM_END
3172 
3173 
3174 JVM_ENTRY(void, JVM_SetThreadPriority(JNIEnv* env, jobject jthread, jint prio))
3175   JVMWrapper("JVM_SetThreadPriority");
3176 
3177   ThreadsListHandle tlh(thread);
3178   oop java_thread = NULL;
3179   JavaThread* receiver = NULL;
3180   bool is_alive = tlh.cv_internal_thread_to_JavaThread(jthread, &receiver, &java_thread);
3181   java_lang_Thread::set_priority(java_thread, (ThreadPriority)prio);
3182 
3183   if (is_alive) {
3184     // jthread refers to a live JavaThread.
3185     Thread::set_priority(receiver, (ThreadPriority)prio);
3186   }
3187   // Implied else: If the JavaThread hasn't started yet, then the
3188   // priority set in the java.lang.Thread object above will be pushed
3189   // down when it does start.
3190 JVM_END
3191 
3192 
3193 JVM_ENTRY(void, JVM_Yield(JNIEnv *env, jclass threadClass))
3194   JVMWrapper("JVM_Yield");
3195   if (os::dont_yield()) return;
3196   HOTSPOT_THREAD_YIELD();
3197   os::naked_yield();
3198 JVM_END
3199 
3200 static void post_thread_sleep_event(EventThreadSleep* event, jlong millis) {
3201   assert(event != NULL, "invariant");
3202   assert(event->should_commit(), "invariant");
3203   event->set_time(millis);
3204   event->commit();
3205 }
3206 
3207 JVM_ENTRY(void, JVM_Sleep(JNIEnv* env, jclass threadClass, jlong millis))
3208   JVMWrapper("JVM_Sleep");
3209 
3210   if (millis < 0) {
3211     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "timeout value is negative");
3212   }
3213 
3214   if (thread->is_interrupted(true) && !HAS_PENDING_EXCEPTION) {
3215     THROW_MSG(vmSymbols::java_lang_InterruptedException(), "sleep interrupted");
3216   }
3217 
3218   // Save current thread state and restore it at the end of this block.
3219   // And set new thread state to SLEEPING.
3220   JavaThreadSleepState jtss(thread);
3221 
3222   HOTSPOT_THREAD_SLEEP_BEGIN(millis);
3223   EventThreadSleep event;
3224 
3225   if (millis == 0) {
3226     os::naked_yield();
3227   } else {
3228     ThreadState old_state = thread->osthread()->get_state();
3229     thread->osthread()->set_state(SLEEPING);
3230     if (!thread->sleep(millis)) { // interrupted
3231       // An asynchronous exception (e.g., ThreadDeathException) could have been thrown on
3232       // us while we were sleeping. We do not overwrite those.
3233       if (!HAS_PENDING_EXCEPTION) {
3234         if (event.should_commit()) {
3235           post_thread_sleep_event(&event, millis);
3236         }
3237         HOTSPOT_THREAD_SLEEP_END(1);
3238 
3239         // TODO-FIXME: THROW_MSG returns which means we will not call set_state()
3240         // to properly restore the thread state.  That's likely wrong.
3241         THROW_MSG(vmSymbols::java_lang_InterruptedException(), "sleep interrupted");
3242       }
3243     }
3244     thread->osthread()->set_state(old_state);
3245   }
3246   if (event.should_commit()) {
3247     post_thread_sleep_event(&event, millis);
3248   }
3249   HOTSPOT_THREAD_SLEEP_END(0);
3250 JVM_END
3251 
3252 JVM_ENTRY(jobject, JVM_CurrentThread(JNIEnv* env, jclass threadClass))
3253   JVMWrapper("JVM_CurrentThread");
3254   oop jthread = thread->threadObj();
3255   assert (thread != NULL, "no current thread!");
3256   return JNIHandles::make_local(env, jthread);
3257 JVM_END
3258 
3259 JVM_ENTRY(void, JVM_Interrupt(JNIEnv* env, jobject jthread))
3260   JVMWrapper("JVM_Interrupt");
3261 
3262   ThreadsListHandle tlh(thread);
3263   JavaThread* receiver = NULL;
3264   bool is_alive = tlh.cv_internal_thread_to_JavaThread(jthread, &receiver, NULL);
3265   if (is_alive) {
3266     // jthread refers to a live JavaThread.
3267     receiver->interrupt();
3268   }
3269 JVM_END
3270 
3271 
3272 // Return true iff the current thread has locked the object passed in
3273 
3274 JVM_ENTRY(jboolean, JVM_HoldsLock(JNIEnv* env, jclass threadClass, jobject obj))
3275   JVMWrapper("JVM_HoldsLock");
3276   assert(THREAD->is_Java_thread(), "sanity check");
3277   if (obj == NULL) {
3278     THROW_(vmSymbols::java_lang_NullPointerException(), JNI_FALSE);
3279   }
3280   Handle h_obj(THREAD, JNIHandles::resolve(obj));
3281   return ObjectSynchronizer::current_thread_holds_lock((JavaThread*)THREAD, h_obj);
3282 JVM_END
3283 
3284 
3285 JVM_ENTRY(void, JVM_DumpAllStacks(JNIEnv* env, jclass))
3286   JVMWrapper("JVM_DumpAllStacks");
3287   VM_PrintThreads op;
3288   VMThread::execute(&op);
3289   if (JvmtiExport::should_post_data_dump()) {
3290     JvmtiExport::post_data_dump();
3291   }
3292 JVM_END
3293 
3294 JVM_ENTRY(void, JVM_SetNativeThreadName(JNIEnv* env, jobject jthread, jstring name))
3295   JVMWrapper("JVM_SetNativeThreadName");
3296 
3297   // We don't use a ThreadsListHandle here because the current thread
3298   // must be alive.
3299   oop java_thread = JNIHandles::resolve_non_null(jthread);
3300   JavaThread* thr = java_lang_Thread::thread(java_thread);
3301   if (thread == thr && !thr->has_attached_via_jni()) {
3302     // Thread naming is only supported for the current thread and
3303     // we don't set the name of an attached thread to avoid stepping
3304     // on other programs.
3305     ResourceMark rm(thread);
3306     const char *thread_name = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(name));
3307     os::set_native_thread_name(thread_name);
3308   }
3309 JVM_END
3310 
3311 // java.lang.SecurityManager ///////////////////////////////////////////////////////////////////////
3312 
3313 JVM_ENTRY(jobjectArray, JVM_GetClassContext(JNIEnv *env))
3314   JVMWrapper("JVM_GetClassContext");
3315   ResourceMark rm(THREAD);
3316   JvmtiVMObjectAllocEventCollector oam;
3317   vframeStream vfst(thread);
3318 
3319   if (SystemDictionary::reflect_CallerSensitive_klass() != NULL) {
3320     // This must only be called from SecurityManager.getClassContext
3321     Method* m = vfst.method();
3322     if (!(m->method_holder() == SystemDictionary::SecurityManager_klass() &&
3323           m->name()          == vmSymbols::getClassContext_name() &&
3324           m->signature()     == vmSymbols::void_class_array_signature())) {
3325       THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), "JVM_GetClassContext must only be called from SecurityManager.getClassContext");
3326     }
3327   }
3328 
3329   // Collect method holders
3330   GrowableArray<Klass*>* klass_array = new GrowableArray<Klass*>();
3331   for (; !vfst.at_end(); vfst.security_next()) {
3332     Method* m = vfst.method();
3333     // Native frames are not returned
3334     if (!m->is_ignored_by_security_stack_walk() && !m->is_native()) {
3335       Klass* holder = m->method_holder();
3336       assert(holder->is_klass(), "just checking");
3337       klass_array->append(holder);
3338     }
3339   }
3340 
3341   // Create result array of type [Ljava/lang/Class;
3342   objArrayOop result = oopFactory::new_objArray(SystemDictionary::Class_klass(), klass_array->length(), CHECK_NULL);
3343   // Fill in mirrors corresponding to method holders
3344   for (int i = 0; i < klass_array->length(); i++) {
3345     result->obj_at_put(i, klass_array->at(i)->java_mirror());
3346   }
3347 
3348   return (jobjectArray) JNIHandles::make_local(env, result);
3349 JVM_END
3350 
3351 
3352 // java.lang.Package ////////////////////////////////////////////////////////////////
3353 
3354 
3355 JVM_ENTRY(jstring, JVM_GetSystemPackage(JNIEnv *env, jstring name))
3356   JVMWrapper("JVM_GetSystemPackage");
3357   ResourceMark rm(THREAD);
3358   JvmtiVMObjectAllocEventCollector oam;
3359   char* str = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(name));
3360   oop result = ClassLoader::get_system_package(str, CHECK_NULL);
3361   return (jstring) JNIHandles::make_local(result);
3362 JVM_END
3363 
3364 
3365 JVM_ENTRY(jobjectArray, JVM_GetSystemPackages(JNIEnv *env))
3366   JVMWrapper("JVM_GetSystemPackages");
3367   JvmtiVMObjectAllocEventCollector oam;
3368   objArrayOop result = ClassLoader::get_system_packages(CHECK_NULL);
3369   return (jobjectArray) JNIHandles::make_local(result);
3370 JVM_END
3371 
3372 
3373 // java.lang.ref.Reference ///////////////////////////////////////////////////////////////
3374 
3375 
3376 JVM_ENTRY(jobject, JVM_GetAndClearReferencePendingList(JNIEnv* env))
3377   JVMWrapper("JVM_GetAndClearReferencePendingList");
3378 
3379   MonitorLocker ml(Heap_lock);
3380   oop ref = Universe::reference_pending_list();
3381   if (ref != NULL) {
3382     Universe::set_reference_pending_list(NULL);
3383   }
3384   return JNIHandles::make_local(env, ref);
3385 JVM_END
3386 
3387 JVM_ENTRY(jboolean, JVM_HasReferencePendingList(JNIEnv* env))
3388   JVMWrapper("JVM_HasReferencePendingList");
3389   MonitorLocker ml(Heap_lock);
3390   return Universe::has_reference_pending_list();
3391 JVM_END
3392 
3393 JVM_ENTRY(void, JVM_WaitForReferencePendingList(JNIEnv* env))
3394   JVMWrapper("JVM_WaitForReferencePendingList");
3395   MonitorLocker ml(Heap_lock);
3396   while (!Universe::has_reference_pending_list()) {
3397     ml.wait();
3398   }
3399 JVM_END
3400 
3401 
3402 // ObjectInputStream ///////////////////////////////////////////////////////////////
3403 
3404 // Return the first user-defined class loader up the execution stack, or null
3405 // if only code from the bootstrap or platform class loader is on the stack.
3406 
3407 JVM_ENTRY(jobject, JVM_LatestUserDefinedLoader(JNIEnv *env))
3408   for (vframeStream vfst(thread); !vfst.at_end(); vfst.next()) {
3409     vfst.skip_reflection_related_frames(); // Only needed for 1.4 reflection
3410     oop loader = vfst.method()->method_holder()->class_loader();
3411     if (loader != NULL && !SystemDictionary::is_platform_class_loader(loader)) {
3412       return JNIHandles::make_local(env, loader);
3413     }
3414   }
3415   return NULL;
3416 JVM_END
3417 
3418 
3419 // Array ///////////////////////////////////////////////////////////////////////////////////////////
3420 
3421 
3422 // resolve array handle and check arguments
3423 static inline arrayOop check_array(JNIEnv *env, jobject arr, bool type_array_only, TRAPS) {
3424   if (arr == NULL) {
3425     THROW_0(vmSymbols::java_lang_NullPointerException());
3426   }
3427   oop a = JNIHandles::resolve_non_null(arr);
3428   if (!a->is_array()) {
3429     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Argument is not an array");
3430   } else if (type_array_only && !a->is_typeArray()) {
3431     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Argument is not an array of primitive type");
3432   }
3433   return arrayOop(a);
3434 }
3435 
3436 
3437 JVM_ENTRY(jint, JVM_GetArrayLength(JNIEnv *env, jobject arr))
3438   JVMWrapper("JVM_GetArrayLength");
3439   arrayOop a = check_array(env, arr, false, CHECK_0);
3440   return a->length();
3441 JVM_END
3442 
3443 
3444 JVM_ENTRY(jobject, JVM_GetArrayElement(JNIEnv *env, jobject arr, jint index))
3445   JVMWrapper("JVM_Array_Get");
3446   JvmtiVMObjectAllocEventCollector oam;
3447   arrayOop a = check_array(env, arr, false, CHECK_NULL);
3448   jvalue value;
3449   BasicType type = Reflection::array_get(&value, a, index, CHECK_NULL);
3450   oop box = Reflection::box(&value, type, CHECK_NULL);
3451   return JNIHandles::make_local(env, box);
3452 JVM_END
3453 
3454 
3455 JVM_ENTRY(jvalue, JVM_GetPrimitiveArrayElement(JNIEnv *env, jobject arr, jint index, jint wCode))
3456   JVMWrapper("JVM_GetPrimitiveArrayElement");
3457   jvalue value;
3458   value.i = 0; // to initialize value before getting used in CHECK
3459   arrayOop a = check_array(env, arr, true, CHECK_(value));
3460   assert(a->is_typeArray(), "just checking");
3461   BasicType type = Reflection::array_get(&value, a, index, CHECK_(value));
3462   BasicType wide_type = (BasicType) wCode;
3463   if (type != wide_type) {
3464     Reflection::widen(&value, type, wide_type, CHECK_(value));
3465   }
3466   return value;
3467 JVM_END
3468 
3469 
3470 JVM_ENTRY(void, JVM_SetArrayElement(JNIEnv *env, jobject arr, jint index, jobject val))
3471   JVMWrapper("JVM_SetArrayElement");
3472   arrayOop a = check_array(env, arr, false, CHECK);
3473   oop box = JNIHandles::resolve(val);
3474   jvalue value;
3475   value.i = 0; // to initialize value before getting used in CHECK
3476   BasicType value_type;
3477   if (a->is_objArray()) {
3478     // Make sure we do no unbox e.g. java/lang/Integer instances when storing into an object array
3479     value_type = Reflection::unbox_for_regular_object(box, &value);
3480   } else {
3481     value_type = Reflection::unbox_for_primitive(box, &value, CHECK);
3482   }
3483   Reflection::array_set(&value, a, index, value_type, CHECK);
3484 JVM_END
3485 
3486 
3487 JVM_ENTRY(void, JVM_SetPrimitiveArrayElement(JNIEnv *env, jobject arr, jint index, jvalue v, unsigned char vCode))
3488   JVMWrapper("JVM_SetPrimitiveArrayElement");
3489   arrayOop a = check_array(env, arr, true, CHECK);
3490   assert(a->is_typeArray(), "just checking");
3491   BasicType value_type = (BasicType) vCode;
3492   Reflection::array_set(&v, a, index, value_type, CHECK);
3493 JVM_END
3494 
3495 
3496 JVM_ENTRY(jobject, JVM_NewArray(JNIEnv *env, jclass eltClass, jint length))
3497   JVMWrapper("JVM_NewArray");
3498   JvmtiVMObjectAllocEventCollector oam;
3499   oop element_mirror = JNIHandles::resolve(eltClass);
3500   oop result = Reflection::reflect_new_array(element_mirror, length, CHECK_NULL);
3501   return JNIHandles::make_local(env, result);
3502 JVM_END
3503 
3504 
3505 JVM_ENTRY(jobject, JVM_NewMultiArray(JNIEnv *env, jclass eltClass, jintArray dim))
3506   JVMWrapper("JVM_NewMultiArray");
3507   JvmtiVMObjectAllocEventCollector oam;
3508   arrayOop dim_array = check_array(env, dim, true, CHECK_NULL);
3509   oop element_mirror = JNIHandles::resolve(eltClass);
3510   assert(dim_array->is_typeArray(), "just checking");
3511   oop result = Reflection::reflect_new_multi_array(element_mirror, typeArrayOop(dim_array), CHECK_NULL);
3512   return JNIHandles::make_local(env, result);
3513 JVM_END
3514 
3515 
3516 // Library support ///////////////////////////////////////////////////////////////////////////
3517 
3518 JVM_ENTRY_NO_ENV(void*, JVM_LoadLibrary(const char* name))
3519   //%note jvm_ct
3520   JVMWrapper("JVM_LoadLibrary");
3521   char ebuf[1024];
3522   void *load_result;
3523   {
3524     ThreadToNativeFromVM ttnfvm(thread);
3525     load_result = os::dll_load(name, ebuf, sizeof ebuf);
3526   }
3527   if (load_result == NULL) {
3528     char msg[1024];
3529     jio_snprintf(msg, sizeof msg, "%s: %s", name, ebuf);
3530     // Since 'ebuf' may contain a string encoded using
3531     // platform encoding scheme, we need to pass
3532     // Exceptions::unsafe_to_utf8 to the new_exception method
3533     // as the last argument. See bug 6367357.
3534     Handle h_exception =
3535       Exceptions::new_exception(thread,
3536                                 vmSymbols::java_lang_UnsatisfiedLinkError(),
3537                                 msg, Exceptions::unsafe_to_utf8);
3538 
3539     THROW_HANDLE_0(h_exception);
3540   }
3541   log_info(library)("Loaded library %s, handle " INTPTR_FORMAT, name, p2i(load_result));
3542   return load_result;
3543 JVM_END
3544 
3545 
3546 JVM_LEAF(void, JVM_UnloadLibrary(void* handle))
3547   JVMWrapper("JVM_UnloadLibrary");
3548   os::dll_unload(handle);
3549   log_info(library)("Unloaded library with handle " INTPTR_FORMAT, p2i(handle));
3550 JVM_END
3551 
3552 
3553 JVM_LEAF(void*, JVM_FindLibraryEntry(void* handle, const char* name))
3554   JVMWrapper("JVM_FindLibraryEntry");
3555   void* find_result = os::dll_lookup(handle, name);
3556   log_info(library)("%s %s in library with handle " INTPTR_FORMAT,
3557                     find_result != NULL ? "Found" : "Failed to find",
3558                     name, p2i(handle));
3559   return find_result;
3560 JVM_END
3561 
3562 
3563 // JNI version ///////////////////////////////////////////////////////////////////////////////
3564 
3565 JVM_LEAF(jboolean, JVM_IsSupportedJNIVersion(jint version))
3566   JVMWrapper("JVM_IsSupportedJNIVersion");
3567   return Threads::is_supported_jni_version_including_1_1(version);
3568 JVM_END
3569 
3570 
3571 // String support ///////////////////////////////////////////////////////////////////////////
3572 
3573 JVM_ENTRY(jstring, JVM_InternString(JNIEnv *env, jstring str))
3574   JVMWrapper("JVM_InternString");
3575   JvmtiVMObjectAllocEventCollector oam;
3576   if (str == NULL) return NULL;
3577   oop string = JNIHandles::resolve_non_null(str);
3578   oop result = StringTable::intern(string, CHECK_NULL);
3579   return (jstring) JNIHandles::make_local(env, result);
3580 JVM_END
3581 
3582 
3583 // VM Raw monitor support //////////////////////////////////////////////////////////////////////
3584 
3585 // VM Raw monitors (not to be confused with JvmtiRawMonitors) are a simple mutual exclusion
3586 // lock (not actually monitors: no wait/notify) that is exported by the VM for use by JDK
3587 // library code. They may be used by JavaThreads and non-JavaThreads and do not participate
3588 // in the safepoint protocol, thread suspension, thread interruption, or anything of that
3589 // nature. JavaThreads will be "in native" when using this API from JDK code.
3590 
3591 
3592 JNIEXPORT void* JNICALL JVM_RawMonitorCreate(void) {
3593   VM_Exit::block_if_vm_exited();
3594   JVMWrapper("JVM_RawMonitorCreate");
3595   return new os::PlatformMutex();
3596 }
3597 
3598 
3599 JNIEXPORT void JNICALL  JVM_RawMonitorDestroy(void *mon) {
3600   VM_Exit::block_if_vm_exited();
3601   JVMWrapper("JVM_RawMonitorDestroy");
3602   delete ((os::PlatformMutex*) mon);
3603 }
3604 
3605 
3606 JNIEXPORT jint JNICALL JVM_RawMonitorEnter(void *mon) {
3607   VM_Exit::block_if_vm_exited();
3608   JVMWrapper("JVM_RawMonitorEnter");
3609   ((os::PlatformMutex*) mon)->lock();
3610   return 0;
3611 }
3612 
3613 
3614 JNIEXPORT void JNICALL JVM_RawMonitorExit(void *mon) {
3615   VM_Exit::block_if_vm_exited();
3616   JVMWrapper("JVM_RawMonitorExit");
3617   ((os::PlatformMutex*) mon)->unlock();
3618 }
3619 
3620 
3621 // Shared JNI/JVM entry points //////////////////////////////////////////////////////////////
3622 
3623 jclass find_class_from_class_loader(JNIEnv* env, Symbol* name, jboolean init,
3624                                     Handle loader, Handle protection_domain,
3625                                     jboolean throwError, TRAPS) {
3626   // Security Note:
3627   //   The Java level wrapper will perform the necessary security check allowing
3628   //   us to pass the NULL as the initiating class loader.  The VM is responsible for
3629   //   the checkPackageAccess relative to the initiating class loader via the
3630   //   protection_domain. The protection_domain is passed as NULL by the java code
3631   //   if there is no security manager in 3-arg Class.forName().
3632   Klass* klass = SystemDictionary::resolve_or_fail(name, loader, protection_domain, throwError != 0, CHECK_NULL);
3633 
3634   // Check if we should initialize the class
3635   if (init && klass->is_instance_klass()) {
3636     klass->initialize(CHECK_NULL);
3637   }
3638   return (jclass) JNIHandles::make_local(env, klass->java_mirror());
3639 }
3640 
3641 
3642 // Method ///////////////////////////////////////////////////////////////////////////////////////////
3643 
3644 JVM_ENTRY(jobject, JVM_InvokeMethod(JNIEnv *env, jobject method, jobject obj, jobjectArray args0))
3645   JVMWrapper("JVM_InvokeMethod");
3646   Handle method_handle;
3647   if (thread->stack_available((address) &method_handle) >= JVMInvokeMethodSlack) {
3648     method_handle = Handle(THREAD, JNIHandles::resolve(method));
3649     Handle receiver(THREAD, JNIHandles::resolve(obj));
3650     objArrayHandle args(THREAD, objArrayOop(JNIHandles::resolve(args0)));
3651     oop result = Reflection::invoke_method(method_handle(), receiver, args, CHECK_NULL);
3652     jobject res = JNIHandles::make_local(env, result);
3653     if (JvmtiExport::should_post_vm_object_alloc()) {
3654       oop ret_type = java_lang_reflect_Method::return_type(method_handle());
3655       assert(ret_type != NULL, "sanity check: ret_type oop must not be NULL!");
3656       if (java_lang_Class::is_primitive(ret_type)) {
3657         // Only for primitive type vm allocates memory for java object.
3658         // See box() method.
3659         JvmtiExport::post_vm_object_alloc(JavaThread::current(), result);
3660       }
3661     }
3662     return res;
3663   } else {
3664     THROW_0(vmSymbols::java_lang_StackOverflowError());
3665   }
3666 JVM_END
3667 
3668 
3669 JVM_ENTRY(jobject, JVM_NewInstanceFromConstructor(JNIEnv *env, jobject c, jobjectArray args0))
3670   JVMWrapper("JVM_NewInstanceFromConstructor");
3671   oop constructor_mirror = JNIHandles::resolve(c);
3672   objArrayHandle args(THREAD, objArrayOop(JNIHandles::resolve(args0)));
3673   oop result = Reflection::invoke_constructor(constructor_mirror, args, CHECK_NULL);
3674   jobject res = JNIHandles::make_local(env, result);
3675   if (JvmtiExport::should_post_vm_object_alloc()) {
3676     JvmtiExport::post_vm_object_alloc(JavaThread::current(), result);
3677   }
3678   return res;
3679 JVM_END
3680 
3681 // Atomic ///////////////////////////////////////////////////////////////////////////////////////////
3682 
3683 JVM_LEAF(jboolean, JVM_SupportsCX8())
3684   JVMWrapper("JVM_SupportsCX8");
3685   return VM_Version::supports_cx8();
3686 JVM_END
3687 
3688 JVM_ENTRY(void, JVM_InitializeFromArchive(JNIEnv* env, jclass cls))
3689   JVMWrapper("JVM_InitializeFromArchive");
3690   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve(cls));
3691   assert(k->is_klass(), "just checking");
3692   HeapShared::initialize_from_archived_subgraph(k);
3693 JVM_END
3694 
3695 JVM_ENTRY_NO_ENV(jlong, JVM_GetRandomSeedForCDSDump())
3696   JVMWrapper("JVM_GetRandomSeedForCDSDump");
3697   if (DumpSharedSpaces) {
3698     const char* release = Abstract_VM_Version::vm_release();
3699     const char* dbg_level = Abstract_VM_Version::jdk_debug_level();
3700     const char* version = VM_Version::internal_vm_info_string();
3701     jlong seed = (jlong)(java_lang_String::hash_code((const jbyte*)release, (int)strlen(release)) ^
3702                          java_lang_String::hash_code((const jbyte*)dbg_level, (int)strlen(dbg_level)) ^
3703                          java_lang_String::hash_code((const jbyte*)version, (int)strlen(version)));
3704     seed += (jlong)Abstract_VM_Version::vm_major_version();
3705     seed += (jlong)Abstract_VM_Version::vm_minor_version();
3706     seed += (jlong)Abstract_VM_Version::vm_security_version();
3707     seed += (jlong)Abstract_VM_Version::vm_patch_version();
3708     if (seed == 0) { // don't let this ever be zero.
3709       seed = 0x87654321;
3710     }
3711     log_debug(cds)("JVM_GetRandomSeedForCDSDump() = " JLONG_FORMAT, seed);
3712     return seed;
3713   } else {
3714     return 0;
3715   }
3716 JVM_END
3717 
3718 // Returns an array of all live Thread objects (VM internal JavaThreads,
3719 // jvmti agent threads, and JNI attaching threads  are skipped)
3720 // See CR 6404306 regarding JNI attaching threads
3721 JVM_ENTRY(jobjectArray, JVM_GetAllThreads(JNIEnv *env, jclass dummy))
3722   ResourceMark rm(THREAD);
3723   ThreadsListEnumerator tle(THREAD, false, false);
3724   JvmtiVMObjectAllocEventCollector oam;
3725 
3726   int num_threads = tle.num_threads();
3727   objArrayOop r = oopFactory::new_objArray(SystemDictionary::Thread_klass(), num_threads, CHECK_NULL);
3728   objArrayHandle threads_ah(THREAD, r);
3729 
3730   for (int i = 0; i < num_threads; i++) {
3731     Handle h = tle.get_threadObj(i);
3732     threads_ah->obj_at_put(i, h());
3733   }
3734 
3735   return (jobjectArray) JNIHandles::make_local(env, threads_ah());
3736 JVM_END
3737 
3738 
3739 // Support for java.lang.Thread.getStackTrace() and getAllStackTraces() methods
3740 // Return StackTraceElement[][], each element is the stack trace of a thread in
3741 // the corresponding entry in the given threads array
3742 JVM_ENTRY(jobjectArray, JVM_DumpThreads(JNIEnv *env, jclass threadClass, jobjectArray threads))
3743   JVMWrapper("JVM_DumpThreads");
3744   JvmtiVMObjectAllocEventCollector oam;
3745 
3746   // Check if threads is null
3747   if (threads == NULL) {
3748     THROW_(vmSymbols::java_lang_NullPointerException(), 0);
3749   }
3750 
3751   objArrayOop a = objArrayOop(JNIHandles::resolve_non_null(threads));
3752   objArrayHandle ah(THREAD, a);
3753   int num_threads = ah->length();
3754   // check if threads is non-empty array
3755   if (num_threads == 0) {
3756     THROW_(vmSymbols::java_lang_IllegalArgumentException(), 0);
3757   }
3758 
3759   // check if threads is not an array of objects of Thread class
3760   Klass* k = ObjArrayKlass::cast(ah->klass())->element_klass();
3761   if (k != SystemDictionary::Thread_klass()) {
3762     THROW_(vmSymbols::java_lang_IllegalArgumentException(), 0);
3763   }
3764 
3765   ResourceMark rm(THREAD);
3766 
3767   GrowableArray<instanceHandle>* thread_handle_array = new GrowableArray<instanceHandle>(num_threads);
3768   for (int i = 0; i < num_threads; i++) {
3769     oop thread_obj = ah->obj_at(i);
3770     instanceHandle h(THREAD, (instanceOop) thread_obj);
3771     thread_handle_array->append(h);
3772   }
3773 
3774   // The JavaThread references in thread_handle_array are validated
3775   // in VM_ThreadDump::doit().
3776   Handle stacktraces = ThreadService::dump_stack_traces(thread_handle_array, num_threads, CHECK_NULL);
3777   return (jobjectArray)JNIHandles::make_local(env, stacktraces());
3778 
3779 JVM_END
3780 
3781 // JVM monitoring and management support
3782 JVM_ENTRY_NO_ENV(void*, JVM_GetManagement(jint version))
3783   return Management::get_jmm_interface(version);
3784 JVM_END
3785 
3786 // com.sun.tools.attach.VirtualMachine agent properties support
3787 //
3788 // Initialize the agent properties with the properties maintained in the VM
3789 JVM_ENTRY(jobject, JVM_InitAgentProperties(JNIEnv *env, jobject properties))
3790   JVMWrapper("JVM_InitAgentProperties");
3791   ResourceMark rm;
3792 
3793   Handle props(THREAD, JNIHandles::resolve_non_null(properties));
3794 
3795   PUTPROP(props, "sun.java.command", Arguments::java_command());
3796   PUTPROP(props, "sun.jvm.flags", Arguments::jvm_flags());
3797   PUTPROP(props, "sun.jvm.args", Arguments::jvm_args());
3798   return properties;
3799 JVM_END
3800 
3801 JVM_ENTRY(jobjectArray, JVM_GetEnclosingMethodInfo(JNIEnv *env, jclass ofClass))
3802 {
3803   JVMWrapper("JVM_GetEnclosingMethodInfo");
3804   JvmtiVMObjectAllocEventCollector oam;
3805 
3806   if (ofClass == NULL) {
3807     return NULL;
3808   }
3809   Handle mirror(THREAD, JNIHandles::resolve_non_null(ofClass));
3810   // Special handling for primitive objects
3811   if (java_lang_Class::is_primitive(mirror())) {
3812     return NULL;
3813   }
3814   Klass* k = java_lang_Class::as_Klass(mirror());
3815   if (!k->is_instance_klass()) {
3816     return NULL;
3817   }
3818   InstanceKlass* ik = InstanceKlass::cast(k);
3819   int encl_method_class_idx = ik->enclosing_method_class_index();
3820   if (encl_method_class_idx == 0) {
3821     return NULL;
3822   }
3823   objArrayOop dest_o = oopFactory::new_objArray(SystemDictionary::Object_klass(), 3, CHECK_NULL);
3824   objArrayHandle dest(THREAD, dest_o);
3825   Klass* enc_k = ik->constants()->klass_at(encl_method_class_idx, CHECK_NULL);
3826   dest->obj_at_put(0, enc_k->java_mirror());
3827   int encl_method_method_idx = ik->enclosing_method_method_index();
3828   if (encl_method_method_idx != 0) {
3829     Symbol* sym = ik->constants()->symbol_at(
3830                         extract_low_short_from_int(
3831                           ik->constants()->name_and_type_at(encl_method_method_idx)));
3832     Handle str = java_lang_String::create_from_symbol(sym, CHECK_NULL);
3833     dest->obj_at_put(1, str());
3834     sym = ik->constants()->symbol_at(
3835               extract_high_short_from_int(
3836                 ik->constants()->name_and_type_at(encl_method_method_idx)));
3837     str = java_lang_String::create_from_symbol(sym, CHECK_NULL);
3838     dest->obj_at_put(2, str());
3839   }
3840   return (jobjectArray) JNIHandles::make_local(dest());
3841 }
3842 JVM_END
3843 
3844 // Returns an array of java.lang.String objects containing the input arguments to the VM.
3845 JVM_ENTRY(jobjectArray, JVM_GetVmArguments(JNIEnv *env))
3846   ResourceMark rm(THREAD);
3847 
3848   if (Arguments::num_jvm_args() == 0 && Arguments::num_jvm_flags() == 0) {
3849     return NULL;
3850   }
3851 
3852   char** vm_flags = Arguments::jvm_flags_array();
3853   char** vm_args = Arguments::jvm_args_array();
3854   int num_flags = Arguments::num_jvm_flags();
3855   int num_args = Arguments::num_jvm_args();
3856 
3857   InstanceKlass* ik = SystemDictionary::String_klass();
3858   objArrayOop r = oopFactory::new_objArray(ik, num_args + num_flags, CHECK_NULL);
3859   objArrayHandle result_h(THREAD, r);
3860 
3861   int index = 0;
3862   for (int j = 0; j < num_flags; j++, index++) {
3863     Handle h = java_lang_String::create_from_platform_dependent_str(vm_flags[j], CHECK_NULL);
3864     result_h->obj_at_put(index, h());
3865   }
3866   for (int i = 0; i < num_args; i++, index++) {
3867     Handle h = java_lang_String::create_from_platform_dependent_str(vm_args[i], CHECK_NULL);
3868     result_h->obj_at_put(index, h());
3869   }
3870   return (jobjectArray) JNIHandles::make_local(env, result_h());
3871 JVM_END
3872 
3873 JVM_ENTRY_NO_ENV(jint, JVM_FindSignal(const char *name))
3874   return os::get_signal_number(name);
3875 JVM_END