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