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