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