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 JVM_ENTRY(jobjectArray, JVM_GetPermittedSubclasses(JNIEnv* env, jclass current))
2111 {
2112   JVMWrapper("JVM_GetPermittedSubclasses");
2113   assert(!java_lang_Class::is_primitive(JNIHandles::resolve_non_null(current)), "should not be");
2114   Klass* c = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(current));
2115   assert(c->is_instance_klass(), "must be");
2116   InstanceKlass* ik = InstanceKlass::cast(c);
2117   {
2118     JvmtiVMObjectAllocEventCollector oam;
2119     Array<u2>* subclasses = ik->permitted_subclasses();
2120     int length = subclasses == NULL ? 0 : subclasses->length();
2121     objArrayOop r = oopFactory::new_objArray(SystemDictionary::String_klass(),
2122                                              length, CHECK_NULL);
2123     objArrayHandle result(THREAD, r);
2124     for (int i = 0; i < length; i++) {
2125       int cp_index = subclasses->at(i);
2126       // This returns <package-name>/<class-name>.
2127       Symbol* klass_name = ik->constants()->klass_name_at(cp_index);
2128       assert(klass_name != NULL, "Unexpected null klass_name");
2129       Handle perm_subtype_h = java_lang_String::create_from_symbol(klass_name, CHECK_NULL);
2130       result->obj_at_put(i, perm_subtype_h());
2131     }
2132     return (jobjectArray)JNIHandles::make_local(THREAD, result());
2133   }
2134 }
2135 JVM_END
2136 
2137 // Constant pool access //////////////////////////////////////////////////////////
2138 
2139 JVM_ENTRY(jobject, JVM_GetClassConstantPool(JNIEnv *env, jclass cls))
2140 {
2141   JVMWrapper("JVM_GetClassConstantPool");
2142   JvmtiVMObjectAllocEventCollector oam;
2143 
2144   // Return null for primitives and arrays
2145   if (!java_lang_Class::is_primitive(JNIHandles::resolve_non_null(cls))) {
2146     Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2147     if (k->is_instance_klass()) {
2148       InstanceKlass* k_h = InstanceKlass::cast(k);
2149       Handle jcp = reflect_ConstantPool::create(CHECK_NULL);
2150       reflect_ConstantPool::set_cp(jcp(), k_h->constants());
2151       return JNIHandles::make_local(jcp());
2152     }
2153   }
2154   return NULL;
2155 }
2156 JVM_END
2157 
2158 
2159 JVM_ENTRY(jint, JVM_ConstantPoolGetSize(JNIEnv *env, jobject obj, jobject unused))
2160 {
2161   JVMWrapper("JVM_ConstantPoolGetSize");
2162   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2163   return cp->length();
2164 }
2165 JVM_END
2166 
2167 
2168 JVM_ENTRY(jclass, JVM_ConstantPoolGetClassAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2169 {
2170   JVMWrapper("JVM_ConstantPoolGetClassAt");
2171   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2172   bounds_check(cp, index, CHECK_NULL);
2173   constantTag tag = cp->tag_at(index);
2174   if (!tag.is_klass() && !tag.is_unresolved_klass()) {
2175     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2176   }
2177   Klass* k = cp->klass_at(index, CHECK_NULL);
2178   return (jclass) JNIHandles::make_local(k->java_mirror());
2179 }
2180 JVM_END
2181 
2182 JVM_ENTRY(jclass, JVM_ConstantPoolGetClassAtIfLoaded(JNIEnv *env, jobject obj, jobject unused, jint index))
2183 {
2184   JVMWrapper("JVM_ConstantPoolGetClassAtIfLoaded");
2185   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2186   bounds_check(cp, index, CHECK_NULL);
2187   constantTag tag = cp->tag_at(index);
2188   if (!tag.is_klass() && !tag.is_unresolved_klass()) {
2189     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2190   }
2191   Klass* k = ConstantPool::klass_at_if_loaded(cp, index);
2192   if (k == NULL) return NULL;
2193   return (jclass) JNIHandles::make_local(k->java_mirror());
2194 }
2195 JVM_END
2196 
2197 static jobject get_method_at_helper(const constantPoolHandle& cp, jint index, bool force_resolution, TRAPS) {
2198   constantTag tag = cp->tag_at(index);
2199   if (!tag.is_method() && !tag.is_interface_method()) {
2200     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2201   }
2202   int klass_ref  = cp->uncached_klass_ref_index_at(index);
2203   Klass* k_o;
2204   if (force_resolution) {
2205     k_o = cp->klass_at(klass_ref, CHECK_NULL);
2206   } else {
2207     k_o = ConstantPool::klass_at_if_loaded(cp, klass_ref);
2208     if (k_o == NULL) return NULL;
2209   }
2210   InstanceKlass* k = InstanceKlass::cast(k_o);
2211   Symbol* name = cp->uncached_name_ref_at(index);
2212   Symbol* sig  = cp->uncached_signature_ref_at(index);
2213   methodHandle m (THREAD, k->find_method(name, sig));
2214   if (m.is_null()) {
2215     THROW_MSG_0(vmSymbols::java_lang_RuntimeException(), "Unable to look up method in target class");
2216   }
2217   oop method;
2218   if (!m->is_initializer() || m->is_static()) {
2219     method = Reflection::new_method(m, true, CHECK_NULL);
2220   } else {
2221     method = Reflection::new_constructor(m, CHECK_NULL);
2222   }
2223   return JNIHandles::make_local(method);
2224 }
2225 
2226 JVM_ENTRY(jobject, JVM_ConstantPoolGetMethodAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2227 {
2228   JVMWrapper("JVM_ConstantPoolGetMethodAt");
2229   JvmtiVMObjectAllocEventCollector oam;
2230   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2231   bounds_check(cp, index, CHECK_NULL);
2232   jobject res = get_method_at_helper(cp, index, true, CHECK_NULL);
2233   return res;
2234 }
2235 JVM_END
2236 
2237 JVM_ENTRY(jobject, JVM_ConstantPoolGetMethodAtIfLoaded(JNIEnv *env, jobject obj, jobject unused, jint index))
2238 {
2239   JVMWrapper("JVM_ConstantPoolGetMethodAtIfLoaded");
2240   JvmtiVMObjectAllocEventCollector oam;
2241   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2242   bounds_check(cp, index, CHECK_NULL);
2243   jobject res = get_method_at_helper(cp, index, false, CHECK_NULL);
2244   return res;
2245 }
2246 JVM_END
2247 
2248 static jobject get_field_at_helper(constantPoolHandle cp, jint index, bool force_resolution, TRAPS) {
2249   constantTag tag = cp->tag_at(index);
2250   if (!tag.is_field()) {
2251     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2252   }
2253   int klass_ref  = cp->uncached_klass_ref_index_at(index);
2254   Klass* k_o;
2255   if (force_resolution) {
2256     k_o = cp->klass_at(klass_ref, CHECK_NULL);
2257   } else {
2258     k_o = ConstantPool::klass_at_if_loaded(cp, klass_ref);
2259     if (k_o == NULL) return NULL;
2260   }
2261   InstanceKlass* k = InstanceKlass::cast(k_o);
2262   Symbol* name = cp->uncached_name_ref_at(index);
2263   Symbol* sig  = cp->uncached_signature_ref_at(index);
2264   fieldDescriptor fd;
2265   Klass* target_klass = k->find_field(name, sig, &fd);
2266   if (target_klass == NULL) {
2267     THROW_MSG_0(vmSymbols::java_lang_RuntimeException(), "Unable to look up field in target class");
2268   }
2269   oop field = Reflection::new_field(&fd, CHECK_NULL);
2270   return JNIHandles::make_local(field);
2271 }
2272 
2273 JVM_ENTRY(jobject, JVM_ConstantPoolGetFieldAt(JNIEnv *env, jobject obj, jobject unusedl, jint index))
2274 {
2275   JVMWrapper("JVM_ConstantPoolGetFieldAt");
2276   JvmtiVMObjectAllocEventCollector oam;
2277   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2278   bounds_check(cp, index, CHECK_NULL);
2279   jobject res = get_field_at_helper(cp, index, true, CHECK_NULL);
2280   return res;
2281 }
2282 JVM_END
2283 
2284 JVM_ENTRY(jobject, JVM_ConstantPoolGetFieldAtIfLoaded(JNIEnv *env, jobject obj, jobject unused, jint index))
2285 {
2286   JVMWrapper("JVM_ConstantPoolGetFieldAtIfLoaded");
2287   JvmtiVMObjectAllocEventCollector oam;
2288   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2289   bounds_check(cp, index, CHECK_NULL);
2290   jobject res = get_field_at_helper(cp, index, false, CHECK_NULL);
2291   return res;
2292 }
2293 JVM_END
2294 
2295 JVM_ENTRY(jobjectArray, JVM_ConstantPoolGetMemberRefInfoAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2296 {
2297   JVMWrapper("JVM_ConstantPoolGetMemberRefInfoAt");
2298   JvmtiVMObjectAllocEventCollector oam;
2299   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2300   bounds_check(cp, index, CHECK_NULL);
2301   constantTag tag = cp->tag_at(index);
2302   if (!tag.is_field_or_method()) {
2303     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2304   }
2305   int klass_ref = cp->uncached_klass_ref_index_at(index);
2306   Symbol*  klass_name  = cp->klass_name_at(klass_ref);
2307   Symbol*  member_name = cp->uncached_name_ref_at(index);
2308   Symbol*  member_sig  = cp->uncached_signature_ref_at(index);
2309   objArrayOop  dest_o = oopFactory::new_objArray(SystemDictionary::String_klass(), 3, CHECK_NULL);
2310   objArrayHandle dest(THREAD, dest_o);
2311   Handle str = java_lang_String::create_from_symbol(klass_name, CHECK_NULL);
2312   dest->obj_at_put(0, str());
2313   str = java_lang_String::create_from_symbol(member_name, CHECK_NULL);
2314   dest->obj_at_put(1, str());
2315   str = java_lang_String::create_from_symbol(member_sig, CHECK_NULL);
2316   dest->obj_at_put(2, str());
2317   return (jobjectArray) JNIHandles::make_local(dest());
2318 }
2319 JVM_END
2320 
2321 JVM_ENTRY(jint, JVM_ConstantPoolGetClassRefIndexAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2322 {
2323   JVMWrapper("JVM_ConstantPoolGetClassRefIndexAt");
2324   JvmtiVMObjectAllocEventCollector oam;
2325   constantPoolHandle cp(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2326   bounds_check(cp, index, CHECK_0);
2327   constantTag tag = cp->tag_at(index);
2328   if (!tag.is_field_or_method()) {
2329     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2330   }
2331   return (jint) cp->uncached_klass_ref_index_at(index);
2332 }
2333 JVM_END
2334 
2335 JVM_ENTRY(jint, JVM_ConstantPoolGetNameAndTypeRefIndexAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2336 {
2337   JVMWrapper("JVM_ConstantPoolGetNameAndTypeRefIndexAt");
2338   JvmtiVMObjectAllocEventCollector oam;
2339   constantPoolHandle cp(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2340   bounds_check(cp, index, CHECK_0);
2341   constantTag tag = cp->tag_at(index);
2342   if (!tag.is_invoke_dynamic() && !tag.is_field_or_method()) {
2343     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2344   }
2345   return (jint) cp->uncached_name_and_type_ref_index_at(index);
2346 }
2347 JVM_END
2348 
2349 JVM_ENTRY(jobjectArray, JVM_ConstantPoolGetNameAndTypeRefInfoAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2350 {
2351   JVMWrapper("JVM_ConstantPoolGetNameAndTypeRefInfoAt");
2352   JvmtiVMObjectAllocEventCollector oam;
2353   constantPoolHandle cp(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2354   bounds_check(cp, index, CHECK_NULL);
2355   constantTag tag = cp->tag_at(index);
2356   if (!tag.is_name_and_type()) {
2357     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2358   }
2359   Symbol* member_name = cp->symbol_at(cp->name_ref_index_at(index));
2360   Symbol* member_sig = cp->symbol_at(cp->signature_ref_index_at(index));
2361   objArrayOop dest_o = oopFactory::new_objArray(SystemDictionary::String_klass(), 2, CHECK_NULL);
2362   objArrayHandle dest(THREAD, dest_o);
2363   Handle str = java_lang_String::create_from_symbol(member_name, CHECK_NULL);
2364   dest->obj_at_put(0, str());
2365   str = java_lang_String::create_from_symbol(member_sig, CHECK_NULL);
2366   dest->obj_at_put(1, str());
2367   return (jobjectArray) JNIHandles::make_local(dest());
2368 }
2369 JVM_END
2370 
2371 JVM_ENTRY(jint, JVM_ConstantPoolGetIntAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2372 {
2373   JVMWrapper("JVM_ConstantPoolGetIntAt");
2374   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2375   bounds_check(cp, index, CHECK_0);
2376   constantTag tag = cp->tag_at(index);
2377   if (!tag.is_int()) {
2378     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2379   }
2380   return cp->int_at(index);
2381 }
2382 JVM_END
2383 
2384 JVM_ENTRY(jlong, JVM_ConstantPoolGetLongAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2385 {
2386   JVMWrapper("JVM_ConstantPoolGetLongAt");
2387   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2388   bounds_check(cp, index, CHECK_(0L));
2389   constantTag tag = cp->tag_at(index);
2390   if (!tag.is_long()) {
2391     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2392   }
2393   return cp->long_at(index);
2394 }
2395 JVM_END
2396 
2397 JVM_ENTRY(jfloat, JVM_ConstantPoolGetFloatAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2398 {
2399   JVMWrapper("JVM_ConstantPoolGetFloatAt");
2400   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2401   bounds_check(cp, index, CHECK_(0.0f));
2402   constantTag tag = cp->tag_at(index);
2403   if (!tag.is_float()) {
2404     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2405   }
2406   return cp->float_at(index);
2407 }
2408 JVM_END
2409 
2410 JVM_ENTRY(jdouble, JVM_ConstantPoolGetDoubleAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2411 {
2412   JVMWrapper("JVM_ConstantPoolGetDoubleAt");
2413   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2414   bounds_check(cp, index, CHECK_(0.0));
2415   constantTag tag = cp->tag_at(index);
2416   if (!tag.is_double()) {
2417     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2418   }
2419   return cp->double_at(index);
2420 }
2421 JVM_END
2422 
2423 JVM_ENTRY(jstring, JVM_ConstantPoolGetStringAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2424 {
2425   JVMWrapper("JVM_ConstantPoolGetStringAt");
2426   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2427   bounds_check(cp, index, CHECK_NULL);
2428   constantTag tag = cp->tag_at(index);
2429   if (!tag.is_string()) {
2430     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2431   }
2432   oop str = cp->string_at(index, CHECK_NULL);
2433   return (jstring) JNIHandles::make_local(str);
2434 }
2435 JVM_END
2436 
2437 JVM_ENTRY(jstring, JVM_ConstantPoolGetUTF8At(JNIEnv *env, jobject obj, jobject unused, jint index))
2438 {
2439   JVMWrapper("JVM_ConstantPoolGetUTF8At");
2440   JvmtiVMObjectAllocEventCollector oam;
2441   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2442   bounds_check(cp, index, CHECK_NULL);
2443   constantTag tag = cp->tag_at(index);
2444   if (!tag.is_symbol()) {
2445     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2446   }
2447   Symbol* sym = cp->symbol_at(index);
2448   Handle str = java_lang_String::create_from_symbol(sym, CHECK_NULL);
2449   return (jstring) JNIHandles::make_local(str());
2450 }
2451 JVM_END
2452 
2453 JVM_ENTRY(jbyte, JVM_ConstantPoolGetTagAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2454 {
2455   JVMWrapper("JVM_ConstantPoolGetTagAt");
2456   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2457   bounds_check(cp, index, CHECK_0);
2458   constantTag tag = cp->tag_at(index);
2459   jbyte result = tag.value();
2460   // If returned tag values are not from the JVM spec, e.g. tags from 100 to 105,
2461   // they are changed to the corresponding tags from the JVM spec, so that java code in
2462   // sun.reflect.ConstantPool will return only tags from the JVM spec, not internal ones.
2463   if (tag.is_klass_or_reference()) {
2464       result = JVM_CONSTANT_Class;
2465   } else if (tag.is_string_index()) {
2466       result = JVM_CONSTANT_String;
2467   } else if (tag.is_method_type_in_error()) {
2468       result = JVM_CONSTANT_MethodType;
2469   } else if (tag.is_method_handle_in_error()) {
2470       result = JVM_CONSTANT_MethodHandle;
2471   } else if (tag.is_dynamic_constant_in_error()) {
2472       result = JVM_CONSTANT_Dynamic;
2473   }
2474   return result;
2475 }
2476 JVM_END
2477 
2478 // Assertion support. //////////////////////////////////////////////////////////
2479 
2480 JVM_ENTRY(jboolean, JVM_DesiredAssertionStatus(JNIEnv *env, jclass unused, jclass cls))
2481   JVMWrapper("JVM_DesiredAssertionStatus");
2482   assert(cls != NULL, "bad class");
2483 
2484   oop r = JNIHandles::resolve(cls);
2485   assert(! java_lang_Class::is_primitive(r), "primitive classes not allowed");
2486   if (java_lang_Class::is_primitive(r)) return false;
2487 
2488   Klass* k = java_lang_Class::as_Klass(r);
2489   assert(k->is_instance_klass(), "must be an instance klass");
2490   if (!k->is_instance_klass()) return false;
2491 
2492   ResourceMark rm(THREAD);
2493   const char* name = k->name()->as_C_string();
2494   bool system_class = k->class_loader() == NULL;
2495   return JavaAssertions::enabled(name, system_class);
2496 
2497 JVM_END
2498 
2499 
2500 // Return a new AssertionStatusDirectives object with the fields filled in with
2501 // command-line assertion arguments (i.e., -ea, -da).
2502 JVM_ENTRY(jobject, JVM_AssertionStatusDirectives(JNIEnv *env, jclass unused))
2503   JVMWrapper("JVM_AssertionStatusDirectives");
2504   JvmtiVMObjectAllocEventCollector oam;
2505   oop asd = JavaAssertions::createAssertionStatusDirectives(CHECK_NULL);
2506   return JNIHandles::make_local(env, asd);
2507 JVM_END
2508 
2509 // Verification ////////////////////////////////////////////////////////////////////////////////
2510 
2511 // Reflection for the verifier /////////////////////////////////////////////////////////////////
2512 
2513 // RedefineClasses support: bug 6214132 caused verification to fail.
2514 // All functions from this section should call the jvmtiThreadSate function:
2515 //   Klass* class_to_verify_considering_redefinition(Klass* klass).
2516 // The function returns a Klass* of the _scratch_class if the verifier
2517 // was invoked in the middle of the class redefinition.
2518 // Otherwise it returns its argument value which is the _the_class Klass*.
2519 // Please, refer to the description in the jvmtiThreadSate.hpp.
2520 
2521 JVM_ENTRY(const char*, JVM_GetClassNameUTF(JNIEnv *env, jclass cls))
2522   JVMWrapper("JVM_GetClassNameUTF");
2523   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2524   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2525   return k->name()->as_utf8();
2526 JVM_END
2527 
2528 
2529 JVM_ENTRY(void, JVM_GetClassCPTypes(JNIEnv *env, jclass cls, unsigned char *types))
2530   JVMWrapper("JVM_GetClassCPTypes");
2531   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2532   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2533   // types will have length zero if this is not an InstanceKlass
2534   // (length is determined by call to JVM_GetClassCPEntriesCount)
2535   if (k->is_instance_klass()) {
2536     ConstantPool* cp = InstanceKlass::cast(k)->constants();
2537     for (int index = cp->length() - 1; index >= 0; index--) {
2538       constantTag tag = cp->tag_at(index);
2539       types[index] = (tag.is_unresolved_klass()) ? (unsigned char) JVM_CONSTANT_Class : tag.value();
2540     }
2541   }
2542 JVM_END
2543 
2544 
2545 JVM_ENTRY(jint, JVM_GetClassCPEntriesCount(JNIEnv *env, jclass cls))
2546   JVMWrapper("JVM_GetClassCPEntriesCount");
2547   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2548   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2549   return (!k->is_instance_klass()) ? 0 : InstanceKlass::cast(k)->constants()->length();
2550 JVM_END
2551 
2552 
2553 JVM_ENTRY(jint, JVM_GetClassFieldsCount(JNIEnv *env, jclass cls))
2554   JVMWrapper("JVM_GetClassFieldsCount");
2555   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2556   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2557   return (!k->is_instance_klass()) ? 0 : InstanceKlass::cast(k)->java_fields_count();
2558 JVM_END
2559 
2560 
2561 JVM_ENTRY(jint, JVM_GetClassMethodsCount(JNIEnv *env, jclass cls))
2562   JVMWrapper("JVM_GetClassMethodsCount");
2563   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2564   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2565   return (!k->is_instance_klass()) ? 0 : InstanceKlass::cast(k)->methods()->length();
2566 JVM_END
2567 
2568 
2569 // The following methods, used for the verifier, are never called with
2570 // array klasses, so a direct cast to InstanceKlass is safe.
2571 // Typically, these methods are called in a loop with bounds determined
2572 // by the results of JVM_GetClass{Fields,Methods}Count, which return
2573 // zero for arrays.
2574 JVM_ENTRY(void, JVM_GetMethodIxExceptionIndexes(JNIEnv *env, jclass cls, jint method_index, unsigned short *exceptions))
2575   JVMWrapper("JVM_GetMethodIxExceptionIndexes");
2576   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2577   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2578   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2579   int length = method->checked_exceptions_length();
2580   if (length > 0) {
2581     CheckedExceptionElement* table= method->checked_exceptions_start();
2582     for (int i = 0; i < length; i++) {
2583       exceptions[i] = table[i].class_cp_index;
2584     }
2585   }
2586 JVM_END
2587 
2588 
2589 JVM_ENTRY(jint, JVM_GetMethodIxExceptionsCount(JNIEnv *env, jclass cls, jint method_index))
2590   JVMWrapper("JVM_GetMethodIxExceptionsCount");
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   return method->checked_exceptions_length();
2595 JVM_END
2596 
2597 
2598 JVM_ENTRY(void, JVM_GetMethodIxByteCode(JNIEnv *env, jclass cls, jint method_index, unsigned char *code))
2599   JVMWrapper("JVM_GetMethodIxByteCode");
2600   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2601   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2602   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2603   memcpy(code, method->code_base(), method->code_size());
2604 JVM_END
2605 
2606 
2607 JVM_ENTRY(jint, JVM_GetMethodIxByteCodeLength(JNIEnv *env, jclass cls, jint method_index))
2608   JVMWrapper("JVM_GetMethodIxByteCodeLength");
2609   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2610   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2611   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2612   return method->code_size();
2613 JVM_END
2614 
2615 
2616 JVM_ENTRY(void, JVM_GetMethodIxExceptionTableEntry(JNIEnv *env, jclass cls, jint method_index, jint entry_index, JVM_ExceptionTableEntryType *entry))
2617   JVMWrapper("JVM_GetMethodIxExceptionTableEntry");
2618   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2619   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2620   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2621   ExceptionTable extable(method);
2622   entry->start_pc   = extable.start_pc(entry_index);
2623   entry->end_pc     = extable.end_pc(entry_index);
2624   entry->handler_pc = extable.handler_pc(entry_index);
2625   entry->catchType  = extable.catch_type_index(entry_index);
2626 JVM_END
2627 
2628 
2629 JVM_ENTRY(jint, JVM_GetMethodIxExceptionTableLength(JNIEnv *env, jclass cls, int method_index))
2630   JVMWrapper("JVM_GetMethodIxExceptionTableLength");
2631   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2632   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2633   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2634   return method->exception_table_length();
2635 JVM_END
2636 
2637 
2638 JVM_ENTRY(jint, JVM_GetMethodIxModifiers(JNIEnv *env, jclass cls, int method_index))
2639   JVMWrapper("JVM_GetMethodIxModifiers");
2640   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2641   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2642   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2643   return method->access_flags().as_int() & JVM_RECOGNIZED_METHOD_MODIFIERS;
2644 JVM_END
2645 
2646 
2647 JVM_ENTRY(jint, JVM_GetFieldIxModifiers(JNIEnv *env, jclass cls, int field_index))
2648   JVMWrapper("JVM_GetFieldIxModifiers");
2649   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2650   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2651   return InstanceKlass::cast(k)->field_access_flags(field_index) & JVM_RECOGNIZED_FIELD_MODIFIERS;
2652 JVM_END
2653 
2654 
2655 JVM_ENTRY(jint, JVM_GetMethodIxLocalsCount(JNIEnv *env, jclass cls, int method_index))
2656   JVMWrapper("JVM_GetMethodIxLocalsCount");
2657   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2658   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2659   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2660   return method->max_locals();
2661 JVM_END
2662 
2663 
2664 JVM_ENTRY(jint, JVM_GetMethodIxArgsSize(JNIEnv *env, jclass cls, int method_index))
2665   JVMWrapper("JVM_GetMethodIxArgsSize");
2666   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2667   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2668   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2669   return method->size_of_parameters();
2670 JVM_END
2671 
2672 
2673 JVM_ENTRY(jint, JVM_GetMethodIxMaxStack(JNIEnv *env, jclass cls, int method_index))
2674   JVMWrapper("JVM_GetMethodIxMaxStack");
2675   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2676   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2677   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2678   return method->verifier_max_stack();
2679 JVM_END
2680 
2681 
2682 JVM_ENTRY(jboolean, JVM_IsConstructorIx(JNIEnv *env, jclass cls, int method_index))
2683   JVMWrapper("JVM_IsConstructorIx");
2684   ResourceMark rm(THREAD);
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->name() == vmSymbols::object_initializer_name();
2689 JVM_END
2690 
2691 
2692 JVM_ENTRY(jboolean, JVM_IsVMGeneratedMethodIx(JNIEnv *env, jclass cls, int method_index))
2693   JVMWrapper("JVM_IsVMGeneratedMethodIx");
2694   ResourceMark rm(THREAD);
2695   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2696   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2697   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2698   return method->is_overpass();
2699 JVM_END
2700 
2701 JVM_ENTRY(const char*, JVM_GetMethodIxNameUTF(JNIEnv *env, jclass cls, jint method_index))
2702   JVMWrapper("JVM_GetMethodIxIxUTF");
2703   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2704   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2705   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2706   return method->name()->as_utf8();
2707 JVM_END
2708 
2709 
2710 JVM_ENTRY(const char*, JVM_GetMethodIxSignatureUTF(JNIEnv *env, jclass cls, jint method_index))
2711   JVMWrapper("JVM_GetMethodIxSignatureUTF");
2712   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2713   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2714   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2715   return method->signature()->as_utf8();
2716 JVM_END
2717 
2718 /**
2719  * All of these JVM_GetCP-xxx methods are used by the old verifier to
2720  * read entries in the constant pool.  Since the old verifier always
2721  * works on a copy of the code, it will not see any rewriting that
2722  * may possibly occur in the middle of verification.  So it is important
2723  * that nothing it calls tries to use the cpCache instead of the raw
2724  * constant pool, so we must use cp->uncached_x methods when appropriate.
2725  */
2726 JVM_ENTRY(const char*, JVM_GetCPFieldNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2727   JVMWrapper("JVM_GetCPFieldNameUTF");
2728   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2729   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2730   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2731   switch (cp->tag_at(cp_index).value()) {
2732     case JVM_CONSTANT_Fieldref:
2733       return cp->uncached_name_ref_at(cp_index)->as_utf8();
2734     default:
2735       fatal("JVM_GetCPFieldNameUTF: illegal constant");
2736   }
2737   ShouldNotReachHere();
2738   return NULL;
2739 JVM_END
2740 
2741 
2742 JVM_ENTRY(const char*, JVM_GetCPMethodNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2743   JVMWrapper("JVM_GetCPMethodNameUTF");
2744   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2745   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2746   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2747   switch (cp->tag_at(cp_index).value()) {
2748     case JVM_CONSTANT_InterfaceMethodref:
2749     case JVM_CONSTANT_Methodref:
2750       return cp->uncached_name_ref_at(cp_index)->as_utf8();
2751     default:
2752       fatal("JVM_GetCPMethodNameUTF: illegal constant");
2753   }
2754   ShouldNotReachHere();
2755   return NULL;
2756 JVM_END
2757 
2758 
2759 JVM_ENTRY(const char*, JVM_GetCPMethodSignatureUTF(JNIEnv *env, jclass cls, jint cp_index))
2760   JVMWrapper("JVM_GetCPMethodSignatureUTF");
2761   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2762   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2763   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2764   switch (cp->tag_at(cp_index).value()) {
2765     case JVM_CONSTANT_InterfaceMethodref:
2766     case JVM_CONSTANT_Methodref:
2767       return cp->uncached_signature_ref_at(cp_index)->as_utf8();
2768     default:
2769       fatal("JVM_GetCPMethodSignatureUTF: illegal constant");
2770   }
2771   ShouldNotReachHere();
2772   return NULL;
2773 JVM_END
2774 
2775 
2776 JVM_ENTRY(const char*, JVM_GetCPFieldSignatureUTF(JNIEnv *env, jclass cls, jint cp_index))
2777   JVMWrapper("JVM_GetCPFieldSignatureUTF");
2778   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2779   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2780   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2781   switch (cp->tag_at(cp_index).value()) {
2782     case JVM_CONSTANT_Fieldref:
2783       return cp->uncached_signature_ref_at(cp_index)->as_utf8();
2784     default:
2785       fatal("JVM_GetCPFieldSignatureUTF: illegal constant");
2786   }
2787   ShouldNotReachHere();
2788   return NULL;
2789 JVM_END
2790 
2791 
2792 JVM_ENTRY(const char*, JVM_GetCPClassNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2793   JVMWrapper("JVM_GetCPClassNameUTF");
2794   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2795   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2796   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2797   Symbol* classname = cp->klass_name_at(cp_index);
2798   return classname->as_utf8();
2799 JVM_END
2800 
2801 
2802 JVM_ENTRY(const char*, JVM_GetCPFieldClassNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2803   JVMWrapper("JVM_GetCPFieldClassNameUTF");
2804   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2805   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2806   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2807   switch (cp->tag_at(cp_index).value()) {
2808     case JVM_CONSTANT_Fieldref: {
2809       int class_index = cp->uncached_klass_ref_index_at(cp_index);
2810       Symbol* classname = cp->klass_name_at(class_index);
2811       return classname->as_utf8();
2812     }
2813     default:
2814       fatal("JVM_GetCPFieldClassNameUTF: illegal constant");
2815   }
2816   ShouldNotReachHere();
2817   return NULL;
2818 JVM_END
2819 
2820 
2821 JVM_ENTRY(const char*, JVM_GetCPMethodClassNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2822   JVMWrapper("JVM_GetCPMethodClassNameUTF");
2823   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2824   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2825   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2826   switch (cp->tag_at(cp_index).value()) {
2827     case JVM_CONSTANT_Methodref:
2828     case JVM_CONSTANT_InterfaceMethodref: {
2829       int class_index = cp->uncached_klass_ref_index_at(cp_index);
2830       Symbol* classname = cp->klass_name_at(class_index);
2831       return classname->as_utf8();
2832     }
2833     default:
2834       fatal("JVM_GetCPMethodClassNameUTF: illegal constant");
2835   }
2836   ShouldNotReachHere();
2837   return NULL;
2838 JVM_END
2839 
2840 
2841 JVM_ENTRY(jint, JVM_GetCPFieldModifiers(JNIEnv *env, jclass cls, int cp_index, jclass called_cls))
2842   JVMWrapper("JVM_GetCPFieldModifiers");
2843   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2844   Klass* k_called = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(called_cls));
2845   k        = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2846   k_called = JvmtiThreadState::class_to_verify_considering_redefinition(k_called, thread);
2847   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2848   ConstantPool* cp_called = InstanceKlass::cast(k_called)->constants();
2849   switch (cp->tag_at(cp_index).value()) {
2850     case JVM_CONSTANT_Fieldref: {
2851       Symbol* name      = cp->uncached_name_ref_at(cp_index);
2852       Symbol* signature = cp->uncached_signature_ref_at(cp_index);
2853       InstanceKlass* ik = InstanceKlass::cast(k_called);
2854       for (JavaFieldStream fs(ik); !fs.done(); fs.next()) {
2855         if (fs.name() == name && fs.signature() == signature) {
2856           return fs.access_flags().as_short() & JVM_RECOGNIZED_FIELD_MODIFIERS;
2857         }
2858       }
2859       return -1;
2860     }
2861     default:
2862       fatal("JVM_GetCPFieldModifiers: illegal constant");
2863   }
2864   ShouldNotReachHere();
2865   return 0;
2866 JVM_END
2867 
2868 
2869 JVM_ENTRY(jint, JVM_GetCPMethodModifiers(JNIEnv *env, jclass cls, int cp_index, jclass called_cls))
2870   JVMWrapper("JVM_GetCPMethodModifiers");
2871   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2872   Klass* k_called = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(called_cls));
2873   k        = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2874   k_called = JvmtiThreadState::class_to_verify_considering_redefinition(k_called, thread);
2875   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2876   switch (cp->tag_at(cp_index).value()) {
2877     case JVM_CONSTANT_Methodref:
2878     case JVM_CONSTANT_InterfaceMethodref: {
2879       Symbol* name      = cp->uncached_name_ref_at(cp_index);
2880       Symbol* signature = cp->uncached_signature_ref_at(cp_index);
2881       Array<Method*>* methods = InstanceKlass::cast(k_called)->methods();
2882       int methods_count = methods->length();
2883       for (int i = 0; i < methods_count; i++) {
2884         Method* method = methods->at(i);
2885         if (method->name() == name && method->signature() == signature) {
2886             return method->access_flags().as_int() & JVM_RECOGNIZED_METHOD_MODIFIERS;
2887         }
2888       }
2889       return -1;
2890     }
2891     default:
2892       fatal("JVM_GetCPMethodModifiers: illegal constant");
2893   }
2894   ShouldNotReachHere();
2895   return 0;
2896 JVM_END
2897 
2898 
2899 // Misc //////////////////////////////////////////////////////////////////////////////////////////////
2900 
2901 JVM_LEAF(void, JVM_ReleaseUTF(const char *utf))
2902   // So long as UTF8::convert_to_utf8 returns resource strings, we don't have to do anything
2903 JVM_END
2904 
2905 
2906 JVM_ENTRY(jboolean, JVM_IsSameClassPackage(JNIEnv *env, jclass class1, jclass class2))
2907   JVMWrapper("JVM_IsSameClassPackage");
2908   oop class1_mirror = JNIHandles::resolve_non_null(class1);
2909   oop class2_mirror = JNIHandles::resolve_non_null(class2);
2910   Klass* klass1 = java_lang_Class::as_Klass(class1_mirror);
2911   Klass* klass2 = java_lang_Class::as_Klass(class2_mirror);
2912   return (jboolean) Reflection::is_same_class_package(klass1, klass2);
2913 JVM_END
2914 
2915 // Printing support //////////////////////////////////////////////////
2916 extern "C" {
2917 
2918 ATTRIBUTE_PRINTF(3, 0)
2919 int jio_vsnprintf(char *str, size_t count, const char *fmt, va_list args) {
2920   // Reject count values that are negative signed values converted to
2921   // unsigned; see bug 4399518, 4417214
2922   if ((intptr_t)count <= 0) return -1;
2923 
2924   int result = os::vsnprintf(str, count, fmt, args);
2925   if (result > 0 && (size_t)result >= count) {
2926     result = -1;
2927   }
2928 
2929   return result;
2930 }
2931 
2932 ATTRIBUTE_PRINTF(3, 4)
2933 int jio_snprintf(char *str, size_t count, const char *fmt, ...) {
2934   va_list args;
2935   int len;
2936   va_start(args, fmt);
2937   len = jio_vsnprintf(str, count, fmt, args);
2938   va_end(args);
2939   return len;
2940 }
2941 
2942 ATTRIBUTE_PRINTF(2, 3)
2943 int jio_fprintf(FILE* f, const char *fmt, ...) {
2944   int len;
2945   va_list args;
2946   va_start(args, fmt);
2947   len = jio_vfprintf(f, fmt, args);
2948   va_end(args);
2949   return len;
2950 }
2951 
2952 ATTRIBUTE_PRINTF(2, 0)
2953 int jio_vfprintf(FILE* f, const char *fmt, va_list args) {
2954   if (Arguments::vfprintf_hook() != NULL) {
2955      return Arguments::vfprintf_hook()(f, fmt, args);
2956   } else {
2957     return vfprintf(f, fmt, args);
2958   }
2959 }
2960 
2961 ATTRIBUTE_PRINTF(1, 2)
2962 JNIEXPORT int jio_printf(const char *fmt, ...) {
2963   int len;
2964   va_list args;
2965   va_start(args, fmt);
2966   len = jio_vfprintf(defaultStream::output_stream(), fmt, args);
2967   va_end(args);
2968   return len;
2969 }
2970 
2971 // HotSpot specific jio method
2972 void jio_print(const char* s, size_t len) {
2973   // Try to make this function as atomic as possible.
2974   if (Arguments::vfprintf_hook() != NULL) {
2975     jio_fprintf(defaultStream::output_stream(), "%.*s", (int)len, s);
2976   } else {
2977     // Make an unused local variable to avoid warning from gcc compiler.
2978     size_t count = ::write(defaultStream::output_fd(), s, (int)len);
2979   }
2980 }
2981 
2982 } // Extern C
2983 
2984 // java.lang.Thread //////////////////////////////////////////////////////////////////////////////
2985 
2986 // In most of the JVM thread support functions we need to access the
2987 // thread through a ThreadsListHandle to prevent it from exiting and
2988 // being reclaimed while we try to operate on it. The exceptions to this
2989 // rule are when operating on the current thread, or if the monitor of
2990 // the target java.lang.Thread is locked at the Java level - in both
2991 // cases the target cannot exit.
2992 
2993 static void thread_entry(JavaThread* thread, TRAPS) {
2994   HandleMark hm(THREAD);
2995   Handle obj(THREAD, thread->threadObj());
2996   JavaValue result(T_VOID);
2997   JavaCalls::call_virtual(&result,
2998                           obj,
2999                           SystemDictionary::Thread_klass(),
3000                           vmSymbols::run_method_name(),
3001                           vmSymbols::void_method_signature(),
3002                           THREAD);
3003 }
3004 
3005 
3006 JVM_ENTRY(void, JVM_StartThread(JNIEnv* env, jobject jthread))
3007   JVMWrapper("JVM_StartThread");
3008   JavaThread *native_thread = NULL;
3009 
3010   // We cannot hold the Threads_lock when we throw an exception,
3011   // due to rank ordering issues. Example:  we might need to grab the
3012   // Heap_lock while we construct the exception.
3013   bool throw_illegal_thread_state = false;
3014 
3015   // We must release the Threads_lock before we can post a jvmti event
3016   // in Thread::start.
3017   {
3018     // Ensure that the C++ Thread and OSThread structures aren't freed before
3019     // we operate.
3020     MutexLocker mu(Threads_lock);
3021 
3022     // Since JDK 5 the java.lang.Thread threadStatus is used to prevent
3023     // re-starting an already started thread, so we should usually find
3024     // that the JavaThread is null. However for a JNI attached thread
3025     // there is a small window between the Thread object being created
3026     // (with its JavaThread set) and the update to its threadStatus, so we
3027     // have to check for this
3028     if (java_lang_Thread::thread(JNIHandles::resolve_non_null(jthread)) != NULL) {
3029       throw_illegal_thread_state = true;
3030     } else {
3031       // We could also check the stillborn flag to see if this thread was already stopped, but
3032       // for historical reasons we let the thread detect that itself when it starts running
3033 
3034       jlong size =
3035              java_lang_Thread::stackSize(JNIHandles::resolve_non_null(jthread));
3036       // Allocate the C++ Thread structure and create the native thread.  The
3037       // stack size retrieved from java is 64-bit signed, but the constructor takes
3038       // size_t (an unsigned type), which may be 32 or 64-bit depending on the platform.
3039       //  - Avoid truncating on 32-bit platforms if size is greater than UINT_MAX.
3040       //  - Avoid passing negative values which would result in really large stacks.
3041       NOT_LP64(if (size > SIZE_MAX) size = SIZE_MAX;)
3042       size_t sz = size > 0 ? (size_t) size : 0;
3043       native_thread = new JavaThread(&thread_entry, sz);
3044 
3045       // At this point it may be possible that no osthread was created for the
3046       // JavaThread due to lack of memory. Check for this situation and throw
3047       // an exception if necessary. Eventually we may want to change this so
3048       // that we only grab the lock if the thread was created successfully -
3049       // then we can also do this check and throw the exception in the
3050       // JavaThread constructor.
3051       if (native_thread->osthread() != NULL) {
3052         // Note: the current thread is not being used within "prepare".
3053         native_thread->prepare(jthread);
3054       }
3055     }
3056   }
3057 
3058   if (throw_illegal_thread_state) {
3059     THROW(vmSymbols::java_lang_IllegalThreadStateException());
3060   }
3061 
3062   assert(native_thread != NULL, "Starting null thread?");
3063 
3064   if (native_thread->osthread() == NULL) {
3065     // No one should hold a reference to the 'native_thread'.
3066     native_thread->smr_delete();
3067     if (JvmtiExport::should_post_resource_exhausted()) {
3068       JvmtiExport::post_resource_exhausted(
3069         JVMTI_RESOURCE_EXHAUSTED_OOM_ERROR | JVMTI_RESOURCE_EXHAUSTED_THREADS,
3070         os::native_thread_creation_failed_msg());
3071     }
3072     THROW_MSG(vmSymbols::java_lang_OutOfMemoryError(),
3073               os::native_thread_creation_failed_msg());
3074   }
3075 
3076 #if INCLUDE_JFR
3077   if (JfrRecorder::is_recording() && EventThreadStart::is_enabled() &&
3078       EventThreadStart::is_stacktrace_enabled()) {
3079     JfrThreadLocal* tl = native_thread->jfr_thread_local();
3080     // skip Thread.start() and Thread.start0()
3081     tl->set_cached_stack_trace_id(JfrStackTraceRepository::record(thread, 2));
3082   }
3083 #endif
3084 
3085   Thread::start(native_thread);
3086 
3087 JVM_END
3088 
3089 
3090 // JVM_Stop is implemented using a VM_Operation, so threads are forced to safepoints
3091 // before the quasi-asynchronous exception is delivered.  This is a little obtrusive,
3092 // but is thought to be reliable and simple. In the case, where the receiver is the
3093 // same thread as the sender, no VM_Operation is needed.
3094 JVM_ENTRY(void, JVM_StopThread(JNIEnv* env, jobject jthread, jobject throwable))
3095   JVMWrapper("JVM_StopThread");
3096 
3097   // A nested ThreadsListHandle will grab the Threads_lock so create
3098   // tlh before we resolve throwable.
3099   ThreadsListHandle tlh(thread);
3100   oop java_throwable = JNIHandles::resolve(throwable);
3101   if (java_throwable == NULL) {
3102     THROW(vmSymbols::java_lang_NullPointerException());
3103   }
3104   oop java_thread = NULL;
3105   JavaThread* receiver = NULL;
3106   bool is_alive = tlh.cv_internal_thread_to_JavaThread(jthread, &receiver, &java_thread);
3107   Events::log_exception(thread,
3108                         "JVM_StopThread thread JavaThread " INTPTR_FORMAT " as oop " INTPTR_FORMAT " [exception " INTPTR_FORMAT "]",
3109                         p2i(receiver), p2i(java_thread), p2i(throwable));
3110 
3111   if (is_alive) {
3112     // jthread refers to a live JavaThread.
3113     if (thread == receiver) {
3114       // Exception is getting thrown at self so no VM_Operation needed.
3115       THROW_OOP(java_throwable);
3116     } else {
3117       // Use a VM_Operation to throw the exception.
3118       Thread::send_async_exception(java_thread, java_throwable);
3119     }
3120   } else {
3121     // Either:
3122     // - target thread has not been started before being stopped, or
3123     // - target thread already terminated
3124     // We could read the threadStatus to determine which case it is
3125     // but that is overkill as it doesn't matter. We must set the
3126     // stillborn flag for the first case, and if the thread has already
3127     // exited setting this flag has no effect.
3128     java_lang_Thread::set_stillborn(java_thread);
3129   }
3130 JVM_END
3131 
3132 
3133 JVM_ENTRY(jboolean, JVM_IsThreadAlive(JNIEnv* env, jobject jthread))
3134   JVMWrapper("JVM_IsThreadAlive");
3135 
3136   oop thread_oop = JNIHandles::resolve_non_null(jthread);
3137   return java_lang_Thread::is_alive(thread_oop);
3138 JVM_END
3139 
3140 
3141 JVM_ENTRY(void, JVM_SuspendThread(JNIEnv* env, jobject jthread))
3142   JVMWrapper("JVM_SuspendThread");
3143 
3144   ThreadsListHandle tlh(thread);
3145   JavaThread* receiver = NULL;
3146   bool is_alive = tlh.cv_internal_thread_to_JavaThread(jthread, &receiver, NULL);
3147   if (is_alive) {
3148     // jthread refers to a live JavaThread.
3149     {
3150       MutexLocker ml(receiver->SR_lock(), Mutex::_no_safepoint_check_flag);
3151       if (receiver->is_external_suspend()) {
3152         // Don't allow nested external suspend requests. We can't return
3153         // an error from this interface so just ignore the problem.
3154         return;
3155       }
3156       if (receiver->is_exiting()) { // thread is in the process of exiting
3157         return;
3158       }
3159       receiver->set_external_suspend();
3160     }
3161 
3162     // java_suspend() will catch threads in the process of exiting
3163     // and will ignore them.
3164     receiver->java_suspend();
3165 
3166     // It would be nice to have the following assertion in all the
3167     // time, but it is possible for a racing resume request to have
3168     // resumed this thread right after we suspended it. Temporarily
3169     // enable this assertion if you are chasing a different kind of
3170     // bug.
3171     //
3172     // assert(java_lang_Thread::thread(receiver->threadObj()) == NULL ||
3173     //   receiver->is_being_ext_suspended(), "thread is not suspended");
3174   }
3175 JVM_END
3176 
3177 
3178 JVM_ENTRY(void, JVM_ResumeThread(JNIEnv* env, jobject jthread))
3179   JVMWrapper("JVM_ResumeThread");
3180 
3181   ThreadsListHandle tlh(thread);
3182   JavaThread* receiver = NULL;
3183   bool is_alive = tlh.cv_internal_thread_to_JavaThread(jthread, &receiver, NULL);
3184   if (is_alive) {
3185     // jthread refers to a live JavaThread.
3186 
3187     // This is the original comment for this Threads_lock grab:
3188     //   We need to *always* get the threads lock here, since this operation cannot be allowed during
3189     //   a safepoint. The safepoint code relies on suspending a thread to examine its state. If other
3190     //   threads randomly resumes threads, then a thread might not be suspended when the safepoint code
3191     //   looks at it.
3192     //
3193     // The above comment dates back to when we had both internal and
3194     // external suspend APIs that shared a common underlying mechanism.
3195     // External suspend is now entirely cooperative and doesn't share
3196     // anything with internal suspend. That said, there are some
3197     // assumptions in the VM that an external resume grabs the
3198     // Threads_lock. We can't drop the Threads_lock grab here until we
3199     // resolve the assumptions that exist elsewhere.
3200     //
3201     MutexLocker ml(Threads_lock);
3202     receiver->java_resume();
3203   }
3204 JVM_END
3205 
3206 
3207 JVM_ENTRY(void, JVM_SetThreadPriority(JNIEnv* env, jobject jthread, jint prio))
3208   JVMWrapper("JVM_SetThreadPriority");
3209 
3210   ThreadsListHandle tlh(thread);
3211   oop java_thread = NULL;
3212   JavaThread* receiver = NULL;
3213   bool is_alive = tlh.cv_internal_thread_to_JavaThread(jthread, &receiver, &java_thread);
3214   java_lang_Thread::set_priority(java_thread, (ThreadPriority)prio);
3215 
3216   if (is_alive) {
3217     // jthread refers to a live JavaThread.
3218     Thread::set_priority(receiver, (ThreadPriority)prio);
3219   }
3220   // Implied else: If the JavaThread hasn't started yet, then the
3221   // priority set in the java.lang.Thread object above will be pushed
3222   // down when it does start.
3223 JVM_END
3224 
3225 
3226 JVM_ENTRY(void, JVM_Yield(JNIEnv *env, jclass threadClass))
3227   JVMWrapper("JVM_Yield");
3228   if (os::dont_yield()) return;
3229   HOTSPOT_THREAD_YIELD();
3230   os::naked_yield();
3231 JVM_END
3232 
3233 static void post_thread_sleep_event(EventThreadSleep* event, jlong millis) {
3234   assert(event != NULL, "invariant");
3235   assert(event->should_commit(), "invariant");
3236   event->set_time(millis);
3237   event->commit();
3238 }
3239 
3240 JVM_ENTRY(void, JVM_Sleep(JNIEnv* env, jclass threadClass, jlong millis))
3241   JVMWrapper("JVM_Sleep");
3242 
3243   if (millis < 0) {
3244     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "timeout value is negative");
3245   }
3246 
3247   if (thread->is_interrupted(true) && !HAS_PENDING_EXCEPTION) {
3248     THROW_MSG(vmSymbols::java_lang_InterruptedException(), "sleep interrupted");
3249   }
3250 
3251   // Save current thread state and restore it at the end of this block.
3252   // And set new thread state to SLEEPING.
3253   JavaThreadSleepState jtss(thread);
3254 
3255   HOTSPOT_THREAD_SLEEP_BEGIN(millis);
3256   EventThreadSleep event;
3257 
3258   if (millis == 0) {
3259     os::naked_yield();
3260   } else {
3261     ThreadState old_state = thread->osthread()->get_state();
3262     thread->osthread()->set_state(SLEEPING);
3263     if (!thread->sleep(millis)) { // interrupted
3264       // An asynchronous exception (e.g., ThreadDeathException) could have been thrown on
3265       // us while we were sleeping. We do not overwrite those.
3266       if (!HAS_PENDING_EXCEPTION) {
3267         if (event.should_commit()) {
3268           post_thread_sleep_event(&event, millis);
3269         }
3270         HOTSPOT_THREAD_SLEEP_END(1);
3271 
3272         // TODO-FIXME: THROW_MSG returns which means we will not call set_state()
3273         // to properly restore the thread state.  That's likely wrong.
3274         THROW_MSG(vmSymbols::java_lang_InterruptedException(), "sleep interrupted");
3275       }
3276     }
3277     thread->osthread()->set_state(old_state);
3278   }
3279   if (event.should_commit()) {
3280     post_thread_sleep_event(&event, millis);
3281   }
3282   HOTSPOT_THREAD_SLEEP_END(0);
3283 JVM_END
3284 
3285 JVM_ENTRY(jobject, JVM_CurrentThread(JNIEnv* env, jclass threadClass))
3286   JVMWrapper("JVM_CurrentThread");
3287   oop jthread = thread->threadObj();
3288   assert (thread != NULL, "no current thread!");
3289   return JNIHandles::make_local(env, jthread);
3290 JVM_END
3291 
3292 JVM_ENTRY(void, JVM_Interrupt(JNIEnv* env, jobject jthread))
3293   JVMWrapper("JVM_Interrupt");
3294 
3295   ThreadsListHandle tlh(thread);
3296   JavaThread* receiver = NULL;
3297   bool is_alive = tlh.cv_internal_thread_to_JavaThread(jthread, &receiver, NULL);
3298   if (is_alive) {
3299     // jthread refers to a live JavaThread.
3300     receiver->interrupt();
3301   }
3302 JVM_END
3303 
3304 
3305 // Return true iff the current thread has locked the object passed in
3306 
3307 JVM_ENTRY(jboolean, JVM_HoldsLock(JNIEnv* env, jclass threadClass, jobject obj))
3308   JVMWrapper("JVM_HoldsLock");
3309   assert(THREAD->is_Java_thread(), "sanity check");
3310   if (obj == NULL) {
3311     THROW_(vmSymbols::java_lang_NullPointerException(), JNI_FALSE);
3312   }
3313   Handle h_obj(THREAD, JNIHandles::resolve(obj));
3314   return ObjectSynchronizer::current_thread_holds_lock((JavaThread*)THREAD, h_obj);
3315 JVM_END
3316 
3317 
3318 JVM_ENTRY(void, JVM_DumpAllStacks(JNIEnv* env, jclass))
3319   JVMWrapper("JVM_DumpAllStacks");
3320   VM_PrintThreads op;
3321   VMThread::execute(&op);
3322   if (JvmtiExport::should_post_data_dump()) {
3323     JvmtiExport::post_data_dump();
3324   }
3325 JVM_END
3326 
3327 JVM_ENTRY(void, JVM_SetNativeThreadName(JNIEnv* env, jobject jthread, jstring name))
3328   JVMWrapper("JVM_SetNativeThreadName");
3329 
3330   // We don't use a ThreadsListHandle here because the current thread
3331   // must be alive.
3332   oop java_thread = JNIHandles::resolve_non_null(jthread);
3333   JavaThread* thr = java_lang_Thread::thread(java_thread);
3334   if (thread == thr && !thr->has_attached_via_jni()) {
3335     // Thread naming is only supported for the current thread and
3336     // we don't set the name of an attached thread to avoid stepping
3337     // on other programs.
3338     ResourceMark rm(thread);
3339     const char *thread_name = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(name));
3340     os::set_native_thread_name(thread_name);
3341   }
3342 JVM_END
3343 
3344 // java.lang.SecurityManager ///////////////////////////////////////////////////////////////////////
3345 
3346 JVM_ENTRY(jobjectArray, JVM_GetClassContext(JNIEnv *env))
3347   JVMWrapper("JVM_GetClassContext");
3348   ResourceMark rm(THREAD);
3349   JvmtiVMObjectAllocEventCollector oam;
3350   vframeStream vfst(thread);
3351 
3352   if (SystemDictionary::reflect_CallerSensitive_klass() != NULL) {
3353     // This must only be called from SecurityManager.getClassContext
3354     Method* m = vfst.method();
3355     if (!(m->method_holder() == SystemDictionary::SecurityManager_klass() &&
3356           m->name()          == vmSymbols::getClassContext_name() &&
3357           m->signature()     == vmSymbols::void_class_array_signature())) {
3358       THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), "JVM_GetClassContext must only be called from SecurityManager.getClassContext");
3359     }
3360   }
3361 
3362   // Collect method holders
3363   GrowableArray<Klass*>* klass_array = new GrowableArray<Klass*>();
3364   for (; !vfst.at_end(); vfst.security_next()) {
3365     Method* m = vfst.method();
3366     // Native frames are not returned
3367     if (!m->is_ignored_by_security_stack_walk() && !m->is_native()) {
3368       Klass* holder = m->method_holder();
3369       assert(holder->is_klass(), "just checking");
3370       klass_array->append(holder);
3371     }
3372   }
3373 
3374   // Create result array of type [Ljava/lang/Class;
3375   objArrayOop result = oopFactory::new_objArray(SystemDictionary::Class_klass(), klass_array->length(), CHECK_NULL);
3376   // Fill in mirrors corresponding to method holders
3377   for (int i = 0; i < klass_array->length(); i++) {
3378     result->obj_at_put(i, klass_array->at(i)->java_mirror());
3379   }
3380 
3381   return (jobjectArray) JNIHandles::make_local(env, result);
3382 JVM_END
3383 
3384 
3385 // java.lang.Package ////////////////////////////////////////////////////////////////
3386 
3387 
3388 JVM_ENTRY(jstring, JVM_GetSystemPackage(JNIEnv *env, jstring name))
3389   JVMWrapper("JVM_GetSystemPackage");
3390   ResourceMark rm(THREAD);
3391   JvmtiVMObjectAllocEventCollector oam;
3392   char* str = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(name));
3393   oop result = ClassLoader::get_system_package(str, CHECK_NULL);
3394   return (jstring) JNIHandles::make_local(result);
3395 JVM_END
3396 
3397 
3398 JVM_ENTRY(jobjectArray, JVM_GetSystemPackages(JNIEnv *env))
3399   JVMWrapper("JVM_GetSystemPackages");
3400   JvmtiVMObjectAllocEventCollector oam;
3401   objArrayOop result = ClassLoader::get_system_packages(CHECK_NULL);
3402   return (jobjectArray) JNIHandles::make_local(result);
3403 JVM_END
3404 
3405 
3406 // java.lang.ref.Reference ///////////////////////////////////////////////////////////////
3407 
3408 
3409 JVM_ENTRY(jobject, JVM_GetAndClearReferencePendingList(JNIEnv* env))
3410   JVMWrapper("JVM_GetAndClearReferencePendingList");
3411 
3412   MonitorLocker ml(Heap_lock);
3413   oop ref = Universe::reference_pending_list();
3414   if (ref != NULL) {
3415     Universe::set_reference_pending_list(NULL);
3416   }
3417   return JNIHandles::make_local(env, ref);
3418 JVM_END
3419 
3420 JVM_ENTRY(jboolean, JVM_HasReferencePendingList(JNIEnv* env))
3421   JVMWrapper("JVM_HasReferencePendingList");
3422   MonitorLocker ml(Heap_lock);
3423   return Universe::has_reference_pending_list();
3424 JVM_END
3425 
3426 JVM_ENTRY(void, JVM_WaitForReferencePendingList(JNIEnv* env))
3427   JVMWrapper("JVM_WaitForReferencePendingList");
3428   MonitorLocker ml(Heap_lock);
3429   while (!Universe::has_reference_pending_list()) {
3430     ml.wait();
3431   }
3432 JVM_END
3433 
3434 
3435 // ObjectInputStream ///////////////////////////////////////////////////////////////
3436 
3437 // Return the first user-defined class loader up the execution stack, or null
3438 // if only code from the bootstrap or platform class loader is on the stack.
3439 
3440 JVM_ENTRY(jobject, JVM_LatestUserDefinedLoader(JNIEnv *env))
3441   for (vframeStream vfst(thread); !vfst.at_end(); vfst.next()) {
3442     vfst.skip_reflection_related_frames(); // Only needed for 1.4 reflection
3443     oop loader = vfst.method()->method_holder()->class_loader();
3444     if (loader != NULL && !SystemDictionary::is_platform_class_loader(loader)) {
3445       return JNIHandles::make_local(env, loader);
3446     }
3447   }
3448   return NULL;
3449 JVM_END
3450 
3451 
3452 // Array ///////////////////////////////////////////////////////////////////////////////////////////
3453 
3454 
3455 // resolve array handle and check arguments
3456 static inline arrayOop check_array(JNIEnv *env, jobject arr, bool type_array_only, TRAPS) {
3457   if (arr == NULL) {
3458     THROW_0(vmSymbols::java_lang_NullPointerException());
3459   }
3460   oop a = JNIHandles::resolve_non_null(arr);
3461   if (!a->is_array()) {
3462     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Argument is not an array");
3463   } else if (type_array_only && !a->is_typeArray()) {
3464     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Argument is not an array of primitive type");
3465   }
3466   return arrayOop(a);
3467 }
3468 
3469 
3470 JVM_ENTRY(jint, JVM_GetArrayLength(JNIEnv *env, jobject arr))
3471   JVMWrapper("JVM_GetArrayLength");
3472   arrayOop a = check_array(env, arr, false, CHECK_0);
3473   return a->length();
3474 JVM_END
3475 
3476 
3477 JVM_ENTRY(jobject, JVM_GetArrayElement(JNIEnv *env, jobject arr, jint index))
3478   JVMWrapper("JVM_Array_Get");
3479   JvmtiVMObjectAllocEventCollector oam;
3480   arrayOop a = check_array(env, arr, false, CHECK_NULL);
3481   jvalue value;
3482   BasicType type = Reflection::array_get(&value, a, index, CHECK_NULL);
3483   oop box = Reflection::box(&value, type, CHECK_NULL);
3484   return JNIHandles::make_local(env, box);
3485 JVM_END
3486 
3487 
3488 JVM_ENTRY(jvalue, JVM_GetPrimitiveArrayElement(JNIEnv *env, jobject arr, jint index, jint wCode))
3489   JVMWrapper("JVM_GetPrimitiveArrayElement");
3490   jvalue value;
3491   value.i = 0; // to initialize value before getting used in CHECK
3492   arrayOop a = check_array(env, arr, true, CHECK_(value));
3493   assert(a->is_typeArray(), "just checking");
3494   BasicType type = Reflection::array_get(&value, a, index, CHECK_(value));
3495   BasicType wide_type = (BasicType) wCode;
3496   if (type != wide_type) {
3497     Reflection::widen(&value, type, wide_type, CHECK_(value));
3498   }
3499   return value;
3500 JVM_END
3501 
3502 
3503 JVM_ENTRY(void, JVM_SetArrayElement(JNIEnv *env, jobject arr, jint index, jobject val))
3504   JVMWrapper("JVM_SetArrayElement");
3505   arrayOop a = check_array(env, arr, false, CHECK);
3506   oop box = JNIHandles::resolve(val);
3507   jvalue value;
3508   value.i = 0; // to initialize value before getting used in CHECK
3509   BasicType value_type;
3510   if (a->is_objArray()) {
3511     // Make sure we do no unbox e.g. java/lang/Integer instances when storing into an object array
3512     value_type = Reflection::unbox_for_regular_object(box, &value);
3513   } else {
3514     value_type = Reflection::unbox_for_primitive(box, &value, CHECK);
3515   }
3516   Reflection::array_set(&value, a, index, value_type, CHECK);
3517 JVM_END
3518 
3519 
3520 JVM_ENTRY(void, JVM_SetPrimitiveArrayElement(JNIEnv *env, jobject arr, jint index, jvalue v, unsigned char vCode))
3521   JVMWrapper("JVM_SetPrimitiveArrayElement");
3522   arrayOop a = check_array(env, arr, true, CHECK);
3523   assert(a->is_typeArray(), "just checking");
3524   BasicType value_type = (BasicType) vCode;
3525   Reflection::array_set(&v, a, index, value_type, CHECK);
3526 JVM_END
3527 
3528 
3529 JVM_ENTRY(jobject, JVM_NewArray(JNIEnv *env, jclass eltClass, jint length))
3530   JVMWrapper("JVM_NewArray");
3531   JvmtiVMObjectAllocEventCollector oam;
3532   oop element_mirror = JNIHandles::resolve(eltClass);
3533   oop result = Reflection::reflect_new_array(element_mirror, length, CHECK_NULL);
3534   return JNIHandles::make_local(env, result);
3535 JVM_END
3536 
3537 
3538 JVM_ENTRY(jobject, JVM_NewMultiArray(JNIEnv *env, jclass eltClass, jintArray dim))
3539   JVMWrapper("JVM_NewMultiArray");
3540   JvmtiVMObjectAllocEventCollector oam;
3541   arrayOop dim_array = check_array(env, dim, true, CHECK_NULL);
3542   oop element_mirror = JNIHandles::resolve(eltClass);
3543   assert(dim_array->is_typeArray(), "just checking");
3544   oop result = Reflection::reflect_new_multi_array(element_mirror, typeArrayOop(dim_array), CHECK_NULL);
3545   return JNIHandles::make_local(env, result);
3546 JVM_END
3547 
3548 
3549 // Library support ///////////////////////////////////////////////////////////////////////////
3550 
3551 JVM_ENTRY_NO_ENV(void*, JVM_LoadLibrary(const char* name))
3552   //%note jvm_ct
3553   JVMWrapper("JVM_LoadLibrary");
3554   char ebuf[1024];
3555   void *load_result;
3556   {
3557     ThreadToNativeFromVM ttnfvm(thread);
3558     load_result = os::dll_load(name, ebuf, sizeof ebuf);
3559   }
3560   if (load_result == NULL) {
3561     char msg[1024];
3562     jio_snprintf(msg, sizeof msg, "%s: %s", name, ebuf);
3563     // Since 'ebuf' may contain a string encoded using
3564     // platform encoding scheme, we need to pass
3565     // Exceptions::unsafe_to_utf8 to the new_exception method
3566     // as the last argument. See bug 6367357.
3567     Handle h_exception =
3568       Exceptions::new_exception(thread,
3569                                 vmSymbols::java_lang_UnsatisfiedLinkError(),
3570                                 msg, Exceptions::unsafe_to_utf8);
3571 
3572     THROW_HANDLE_0(h_exception);
3573   }
3574   log_info(library)("Loaded library %s, handle " INTPTR_FORMAT, name, p2i(load_result));
3575   return load_result;
3576 JVM_END
3577 
3578 
3579 JVM_LEAF(void, JVM_UnloadLibrary(void* handle))
3580   JVMWrapper("JVM_UnloadLibrary");
3581   os::dll_unload(handle);
3582   log_info(library)("Unloaded library with handle " INTPTR_FORMAT, p2i(handle));
3583 JVM_END
3584 
3585 
3586 JVM_LEAF(void*, JVM_FindLibraryEntry(void* handle, const char* name))
3587   JVMWrapper("JVM_FindLibraryEntry");
3588   void* find_result = os::dll_lookup(handle, name);
3589   log_info(library)("%s %s in library with handle " INTPTR_FORMAT,
3590                     find_result != NULL ? "Found" : "Failed to find",
3591                     name, p2i(handle));
3592   return find_result;
3593 JVM_END
3594 
3595 
3596 // JNI version ///////////////////////////////////////////////////////////////////////////////
3597 
3598 JVM_LEAF(jboolean, JVM_IsSupportedJNIVersion(jint version))
3599   JVMWrapper("JVM_IsSupportedJNIVersion");
3600   return Threads::is_supported_jni_version_including_1_1(version);
3601 JVM_END
3602 
3603 
3604 // String support ///////////////////////////////////////////////////////////////////////////
3605 
3606 JVM_ENTRY(jstring, JVM_InternString(JNIEnv *env, jstring str))
3607   JVMWrapper("JVM_InternString");
3608   JvmtiVMObjectAllocEventCollector oam;
3609   if (str == NULL) return NULL;
3610   oop string = JNIHandles::resolve_non_null(str);
3611   oop result = StringTable::intern(string, CHECK_NULL);
3612   return (jstring) JNIHandles::make_local(env, result);
3613 JVM_END
3614 
3615 
3616 // VM Raw monitor support //////////////////////////////////////////////////////////////////////
3617 
3618 // VM Raw monitors (not to be confused with JvmtiRawMonitors) are a simple mutual exclusion
3619 // lock (not actually monitors: no wait/notify) that is exported by the VM for use by JDK
3620 // library code. They may be used by JavaThreads and non-JavaThreads and do not participate
3621 // in the safepoint protocol, thread suspension, thread interruption, or anything of that
3622 // nature. JavaThreads will be "in native" when using this API from JDK code.
3623 
3624 
3625 JNIEXPORT void* JNICALL JVM_RawMonitorCreate(void) {
3626   VM_Exit::block_if_vm_exited();
3627   JVMWrapper("JVM_RawMonitorCreate");
3628   return new os::PlatformMutex();
3629 }
3630 
3631 
3632 JNIEXPORT void JNICALL  JVM_RawMonitorDestroy(void *mon) {
3633   VM_Exit::block_if_vm_exited();
3634   JVMWrapper("JVM_RawMonitorDestroy");
3635   delete ((os::PlatformMutex*) mon);
3636 }
3637 
3638 
3639 JNIEXPORT jint JNICALL JVM_RawMonitorEnter(void *mon) {
3640   VM_Exit::block_if_vm_exited();
3641   JVMWrapper("JVM_RawMonitorEnter");
3642   ((os::PlatformMutex*) mon)->lock();
3643   return 0;
3644 }
3645 
3646 
3647 JNIEXPORT void JNICALL JVM_RawMonitorExit(void *mon) {
3648   VM_Exit::block_if_vm_exited();
3649   JVMWrapper("JVM_RawMonitorExit");
3650   ((os::PlatformMutex*) mon)->unlock();
3651 }
3652 
3653 
3654 // Shared JNI/JVM entry points //////////////////////////////////////////////////////////////
3655 
3656 jclass find_class_from_class_loader(JNIEnv* env, Symbol* name, jboolean init,
3657                                     Handle loader, Handle protection_domain,
3658                                     jboolean throwError, TRAPS) {
3659   // Security Note:
3660   //   The Java level wrapper will perform the necessary security check allowing
3661   //   us to pass the NULL as the initiating class loader.  The VM is responsible for
3662   //   the checkPackageAccess relative to the initiating class loader via the
3663   //   protection_domain. The protection_domain is passed as NULL by the java code
3664   //   if there is no security manager in 3-arg Class.forName().
3665   Klass* klass = SystemDictionary::resolve_or_fail(name, loader, protection_domain, throwError != 0, CHECK_NULL);
3666 
3667   // Check if we should initialize the class
3668   if (init && klass->is_instance_klass()) {
3669     klass->initialize(CHECK_NULL);
3670   }
3671   return (jclass) JNIHandles::make_local(env, klass->java_mirror());
3672 }
3673 
3674 
3675 // Method ///////////////////////////////////////////////////////////////////////////////////////////
3676 
3677 JVM_ENTRY(jobject, JVM_InvokeMethod(JNIEnv *env, jobject method, jobject obj, jobjectArray args0))
3678   JVMWrapper("JVM_InvokeMethod");
3679   Handle method_handle;
3680   if (thread->stack_available((address) &method_handle) >= JVMInvokeMethodSlack) {
3681     method_handle = Handle(THREAD, JNIHandles::resolve(method));
3682     Handle receiver(THREAD, JNIHandles::resolve(obj));
3683     objArrayHandle args(THREAD, objArrayOop(JNIHandles::resolve(args0)));
3684     oop result = Reflection::invoke_method(method_handle(), receiver, args, CHECK_NULL);
3685     jobject res = JNIHandles::make_local(env, result);
3686     if (JvmtiExport::should_post_vm_object_alloc()) {
3687       oop ret_type = java_lang_reflect_Method::return_type(method_handle());
3688       assert(ret_type != NULL, "sanity check: ret_type oop must not be NULL!");
3689       if (java_lang_Class::is_primitive(ret_type)) {
3690         // Only for primitive type vm allocates memory for java object.
3691         // See box() method.
3692         JvmtiExport::post_vm_object_alloc(JavaThread::current(), result);
3693       }
3694     }
3695     return res;
3696   } else {
3697     THROW_0(vmSymbols::java_lang_StackOverflowError());
3698   }
3699 JVM_END
3700 
3701 
3702 JVM_ENTRY(jobject, JVM_NewInstanceFromConstructor(JNIEnv *env, jobject c, jobjectArray args0))
3703   JVMWrapper("JVM_NewInstanceFromConstructor");
3704   oop constructor_mirror = JNIHandles::resolve(c);
3705   objArrayHandle args(THREAD, objArrayOop(JNIHandles::resolve(args0)));
3706   oop result = Reflection::invoke_constructor(constructor_mirror, args, CHECK_NULL);
3707   jobject res = JNIHandles::make_local(env, result);
3708   if (JvmtiExport::should_post_vm_object_alloc()) {
3709     JvmtiExport::post_vm_object_alloc(JavaThread::current(), result);
3710   }
3711   return res;
3712 JVM_END
3713 
3714 // Atomic ///////////////////////////////////////////////////////////////////////////////////////////
3715 
3716 JVM_LEAF(jboolean, JVM_SupportsCX8())
3717   JVMWrapper("JVM_SupportsCX8");
3718   return VM_Version::supports_cx8();
3719 JVM_END
3720 
3721 JVM_ENTRY(void, JVM_InitializeFromArchive(JNIEnv* env, jclass cls))
3722   JVMWrapper("JVM_InitializeFromArchive");
3723   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve(cls));
3724   assert(k->is_klass(), "just checking");
3725   HeapShared::initialize_from_archived_subgraph(k);
3726 JVM_END
3727 
3728 JVM_ENTRY_NO_ENV(jlong, JVM_GetRandomSeedForCDSDump())
3729   JVMWrapper("JVM_GetRandomSeedForCDSDump");
3730   if (DumpSharedSpaces) {
3731     const char* release = Abstract_VM_Version::vm_release();
3732     const char* dbg_level = Abstract_VM_Version::jdk_debug_level();
3733     const char* version = VM_Version::internal_vm_info_string();
3734     jlong seed = (jlong)(java_lang_String::hash_code((const jbyte*)release, (int)strlen(release)) ^
3735                          java_lang_String::hash_code((const jbyte*)dbg_level, (int)strlen(dbg_level)) ^
3736                          java_lang_String::hash_code((const jbyte*)version, (int)strlen(version)));
3737     seed += (jlong)Abstract_VM_Version::vm_major_version();
3738     seed += (jlong)Abstract_VM_Version::vm_minor_version();
3739     seed += (jlong)Abstract_VM_Version::vm_security_version();
3740     seed += (jlong)Abstract_VM_Version::vm_patch_version();
3741     if (seed == 0) { // don't let this ever be zero.
3742       seed = 0x87654321;
3743     }
3744     log_debug(cds)("JVM_GetRandomSeedForCDSDump() = " JLONG_FORMAT, seed);
3745     return seed;
3746   } else {
3747     return 0;
3748   }
3749 JVM_END
3750 
3751 // Returns an array of all live Thread objects (VM internal JavaThreads,
3752 // jvmti agent threads, and JNI attaching threads  are skipped)
3753 // See CR 6404306 regarding JNI attaching threads
3754 JVM_ENTRY(jobjectArray, JVM_GetAllThreads(JNIEnv *env, jclass dummy))
3755   ResourceMark rm(THREAD);
3756   ThreadsListEnumerator tle(THREAD, false, false);
3757   JvmtiVMObjectAllocEventCollector oam;
3758 
3759   int num_threads = tle.num_threads();
3760   objArrayOop r = oopFactory::new_objArray(SystemDictionary::Thread_klass(), num_threads, CHECK_NULL);
3761   objArrayHandle threads_ah(THREAD, r);
3762 
3763   for (int i = 0; i < num_threads; i++) {
3764     Handle h = tle.get_threadObj(i);
3765     threads_ah->obj_at_put(i, h());
3766   }
3767 
3768   return (jobjectArray) JNIHandles::make_local(env, threads_ah());
3769 JVM_END
3770 
3771 
3772 // Support for java.lang.Thread.getStackTrace() and getAllStackTraces() methods
3773 // Return StackTraceElement[][], each element is the stack trace of a thread in
3774 // the corresponding entry in the given threads array
3775 JVM_ENTRY(jobjectArray, JVM_DumpThreads(JNIEnv *env, jclass threadClass, jobjectArray threads))
3776   JVMWrapper("JVM_DumpThreads");
3777   JvmtiVMObjectAllocEventCollector oam;
3778 
3779   // Check if threads is null
3780   if (threads == NULL) {
3781     THROW_(vmSymbols::java_lang_NullPointerException(), 0);
3782   }
3783 
3784   objArrayOop a = objArrayOop(JNIHandles::resolve_non_null(threads));
3785   objArrayHandle ah(THREAD, a);
3786   int num_threads = ah->length();
3787   // check if threads is non-empty array
3788   if (num_threads == 0) {
3789     THROW_(vmSymbols::java_lang_IllegalArgumentException(), 0);
3790   }
3791 
3792   // check if threads is not an array of objects of Thread class
3793   Klass* k = ObjArrayKlass::cast(ah->klass())->element_klass();
3794   if (k != SystemDictionary::Thread_klass()) {
3795     THROW_(vmSymbols::java_lang_IllegalArgumentException(), 0);
3796   }
3797 
3798   ResourceMark rm(THREAD);
3799 
3800   GrowableArray<instanceHandle>* thread_handle_array = new GrowableArray<instanceHandle>(num_threads);
3801   for (int i = 0; i < num_threads; i++) {
3802     oop thread_obj = ah->obj_at(i);
3803     instanceHandle h(THREAD, (instanceOop) thread_obj);
3804     thread_handle_array->append(h);
3805   }
3806 
3807   // The JavaThread references in thread_handle_array are validated
3808   // in VM_ThreadDump::doit().
3809   Handle stacktraces = ThreadService::dump_stack_traces(thread_handle_array, num_threads, CHECK_NULL);
3810   return (jobjectArray)JNIHandles::make_local(env, stacktraces());
3811 
3812 JVM_END
3813 
3814 // JVM monitoring and management support
3815 JVM_ENTRY_NO_ENV(void*, JVM_GetManagement(jint version))
3816   return Management::get_jmm_interface(version);
3817 JVM_END
3818 
3819 // com.sun.tools.attach.VirtualMachine agent properties support
3820 //
3821 // Initialize the agent properties with the properties maintained in the VM
3822 JVM_ENTRY(jobject, JVM_InitAgentProperties(JNIEnv *env, jobject properties))
3823   JVMWrapper("JVM_InitAgentProperties");
3824   ResourceMark rm;
3825 
3826   Handle props(THREAD, JNIHandles::resolve_non_null(properties));
3827 
3828   PUTPROP(props, "sun.java.command", Arguments::java_command());
3829   PUTPROP(props, "sun.jvm.flags", Arguments::jvm_flags());
3830   PUTPROP(props, "sun.jvm.args", Arguments::jvm_args());
3831   return properties;
3832 JVM_END
3833 
3834 JVM_ENTRY(jobjectArray, JVM_GetEnclosingMethodInfo(JNIEnv *env, jclass ofClass))
3835 {
3836   JVMWrapper("JVM_GetEnclosingMethodInfo");
3837   JvmtiVMObjectAllocEventCollector oam;
3838 
3839   if (ofClass == NULL) {
3840     return NULL;
3841   }
3842   Handle mirror(THREAD, JNIHandles::resolve_non_null(ofClass));
3843   // Special handling for primitive objects
3844   if (java_lang_Class::is_primitive(mirror())) {
3845     return NULL;
3846   }
3847   Klass* k = java_lang_Class::as_Klass(mirror());
3848   if (!k->is_instance_klass()) {
3849     return NULL;
3850   }
3851   InstanceKlass* ik = InstanceKlass::cast(k);
3852   int encl_method_class_idx = ik->enclosing_method_class_index();
3853   if (encl_method_class_idx == 0) {
3854     return NULL;
3855   }
3856   objArrayOop dest_o = oopFactory::new_objArray(SystemDictionary::Object_klass(), 3, CHECK_NULL);
3857   objArrayHandle dest(THREAD, dest_o);
3858   Klass* enc_k = ik->constants()->klass_at(encl_method_class_idx, CHECK_NULL);
3859   dest->obj_at_put(0, enc_k->java_mirror());
3860   int encl_method_method_idx = ik->enclosing_method_method_index();
3861   if (encl_method_method_idx != 0) {
3862     Symbol* sym = ik->constants()->symbol_at(
3863                         extract_low_short_from_int(
3864                           ik->constants()->name_and_type_at(encl_method_method_idx)));
3865     Handle str = java_lang_String::create_from_symbol(sym, CHECK_NULL);
3866     dest->obj_at_put(1, str());
3867     sym = ik->constants()->symbol_at(
3868               extract_high_short_from_int(
3869                 ik->constants()->name_and_type_at(encl_method_method_idx)));
3870     str = java_lang_String::create_from_symbol(sym, CHECK_NULL);
3871     dest->obj_at_put(2, str());
3872   }
3873   return (jobjectArray) JNIHandles::make_local(dest());
3874 }
3875 JVM_END
3876 
3877 // Returns an array of java.lang.String objects containing the input arguments to the VM.
3878 JVM_ENTRY(jobjectArray, JVM_GetVmArguments(JNIEnv *env))
3879   ResourceMark rm(THREAD);
3880 
3881   if (Arguments::num_jvm_args() == 0 && Arguments::num_jvm_flags() == 0) {
3882     return NULL;
3883   }
3884 
3885   char** vm_flags = Arguments::jvm_flags_array();
3886   char** vm_args = Arguments::jvm_args_array();
3887   int num_flags = Arguments::num_jvm_flags();
3888   int num_args = Arguments::num_jvm_args();
3889 
3890   InstanceKlass* ik = SystemDictionary::String_klass();
3891   objArrayOop r = oopFactory::new_objArray(ik, num_args + num_flags, CHECK_NULL);
3892   objArrayHandle result_h(THREAD, r);
3893 
3894   int index = 0;
3895   for (int j = 0; j < num_flags; j++, index++) {
3896     Handle h = java_lang_String::create_from_platform_dependent_str(vm_flags[j], CHECK_NULL);
3897     result_h->obj_at_put(index, h());
3898   }
3899   for (int i = 0; i < num_args; i++, index++) {
3900     Handle h = java_lang_String::create_from_platform_dependent_str(vm_args[i], CHECK_NULL);
3901     result_h->obj_at_put(index, h());
3902   }
3903   return (jobjectArray) JNIHandles::make_local(env, result_h());
3904 JVM_END
3905 
3906 JVM_ENTRY_NO_ENV(jint, JVM_FindSignal(const char *name))
3907   return os::get_signal_number(name);
3908 JVM_END