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