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