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