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