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