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