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