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