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