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