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