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