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   const int inner_class_info_index = 0;
1305   const int outer_class_info_index = 1;
1306 
1307   JvmtiVMObjectAllocEventCollector oam;
1308   // ofClass is a reference to a java_lang_Class object. The mirror object
1309   // of an instanceKlass
1310 
1311   if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(ofClass)) ||
1312       ! Klass::cast(java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(ofClass)))->oop_is_instance()) {
1313     oop result = oopFactory::new_objArray(SystemDictionary::Class_klass(), 0, CHECK_NULL);
1314     return (jobjectArray)JNIHandles::make_local(env, result);
1315   }
1316 
1317   instanceKlassHandle k(thread, java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(ofClass)));
1318 
1319   if (k->inner_classes()->length() == 0) {
1320     // Neither an inner nor outer class
1321     oop result = oopFactory::new_objArray(SystemDictionary::Class_klass(), 0, CHECK_NULL);
1322     return (jobjectArray)JNIHandles::make_local(env, result);
1323   }
1324 
1325   // find inner class info
1326   typeArrayHandle    icls(thread, k->inner_classes());
1327   constantPoolHandle cp(thread, k->constants());
1328   int length = icls->length();
1329 
1330   // Allocate temp. result array
1331   objArrayOop r = oopFactory::new_objArray(SystemDictionary::Class_klass(), length/4, CHECK_NULL);
1332   objArrayHandle result (THREAD, r);
1333   int members = 0;
1334 
1335   for(int i = 0; i < length; i += 4) {
1336     int ioff = icls->ushort_at(i + inner_class_info_index);
1337     int ooff = icls->ushort_at(i + outer_class_info_index);
1338 
1339     if (ioff != 0 && ooff != 0) {
1340       // Check to see if the name matches the class we're looking for
1341       // before attempting to find the class.
1342       if (cp->klass_name_at_matches(k, ooff)) {
1343         klassOop outer_klass = cp->klass_at(ooff, CHECK_NULL);
1344         if (outer_klass == k()) {
1345            klassOop ik = cp->klass_at(ioff, CHECK_NULL);
1346            instanceKlassHandle inner_klass (THREAD, ik);
1347 
1348            // Throws an exception if outer klass has not declared k as
1349            // an inner klass
1350            Reflection::check_for_inner_class(k, inner_klass, true, CHECK_NULL);
1351 
1352            result->obj_at_put(members, inner_klass->java_mirror());
1353            members++;
1354         }
1355       }
1356     }
1357   }
1358 
1359   if (members != length) {
1360     // Return array of right length
1361     objArrayOop res = oopFactory::new_objArray(SystemDictionary::Class_klass(), members, CHECK_NULL);
1362     for(int i = 0; i < members; i++) {
1363       res->obj_at_put(i, result->obj_at(i));
1364     }
1365     return (jobjectArray)JNIHandles::make_local(env, res);
1366   }
1367 
1368   return (jobjectArray)JNIHandles::make_local(env, result());
1369 JVM_END
1370 
1371 
1372 JVM_ENTRY(jclass, JVM_GetDeclaringClass(JNIEnv *env, jclass ofClass))
1373 {
1374   // ofClass is a reference to a java_lang_Class object.
1375   if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(ofClass)) ||
1376       ! Klass::cast(java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(ofClass)))->oop_is_instance()) {
1377     return NULL;
1378   }
1379 
1380   bool inner_is_member = false;
1381   klassOop outer_klass
1382     = instanceKlass::cast(java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(ofClass))
1383                           )->compute_enclosing_class(&inner_is_member, CHECK_NULL);
1384   if (outer_klass == NULL)  return NULL;  // already a top-level class
1385   if (!inner_is_member)  return NULL;     // an anonymous class (inside a method)
1386   return (jclass) JNIHandles::make_local(env, Klass::cast(outer_klass)->java_mirror());
1387 }
1388 JVM_END
1389 
1390 // should be in instanceKlass.cpp, but is here for historical reasons
1391 klassOop instanceKlass::compute_enclosing_class_impl(instanceKlassHandle k,
1392                                                      bool* inner_is_member,
1393                                                      TRAPS) {
1394   Thread* thread = THREAD;
1395   const int inner_class_info_index = inner_class_inner_class_info_offset;
1396   const int outer_class_info_index = inner_class_outer_class_info_offset;
1397 
1398   if (k->inner_classes()->length() == 0) {
1399     // No inner class info => no declaring class
1400     return NULL;
1401   }
1402 
1403   typeArrayHandle i_icls(thread, k->inner_classes());
1404   constantPoolHandle i_cp(thread, k->constants());
1405   int i_length = i_icls->length();
1406 
1407   bool found = false;
1408   klassOop ok;
1409   instanceKlassHandle outer_klass;
1410   *inner_is_member = false;
1411 
1412   // Find inner_klass attribute
1413   for (int i = 0; i < i_length && !found; i += inner_class_next_offset) {
1414     int ioff = i_icls->ushort_at(i + inner_class_info_index);
1415     int ooff = i_icls->ushort_at(i + outer_class_info_index);
1416     int noff = i_icls->ushort_at(i + inner_class_inner_name_offset);
1417     if (ioff != 0) {
1418       // Check to see if the name matches the class we're looking for
1419       // before attempting to find the class.
1420       if (i_cp->klass_name_at_matches(k, ioff)) {
1421         klassOop inner_klass = i_cp->klass_at(ioff, CHECK_NULL);
1422         found = (k() == inner_klass);
1423         if (found && ooff != 0) {
1424           ok = i_cp->klass_at(ooff, CHECK_NULL);
1425           outer_klass = instanceKlassHandle(thread, ok);
1426           *inner_is_member = true;
1427         }
1428       }
1429     }
1430   }
1431 
1432   if (found && outer_klass.is_null()) {
1433     // It may be anonymous; try for that.
1434     int encl_method_class_idx = k->enclosing_method_class_index();
1435     if (encl_method_class_idx != 0) {
1436       ok = i_cp->klass_at(encl_method_class_idx, CHECK_NULL);
1437       outer_klass = instanceKlassHandle(thread, ok);
1438       *inner_is_member = false;
1439     }
1440   }
1441 
1442   // If no inner class attribute found for this class.
1443   if (outer_klass.is_null())  return NULL;
1444 
1445   // Throws an exception if outer klass has not declared k as an inner klass
1446   // We need evidence that each klass knows about the other, or else
1447   // the system could allow a spoof of an inner class to gain access rights.
1448   Reflection::check_for_inner_class(outer_klass, k, *inner_is_member, CHECK_NULL);
1449   return outer_klass();
1450 }
1451 
1452 JVM_ENTRY(jstring, JVM_GetClassSignature(JNIEnv *env, jclass cls))
1453   assert (cls != NULL, "illegal class");
1454   JVMWrapper("JVM_GetClassSignature");
1455   JvmtiVMObjectAllocEventCollector oam;
1456   ResourceMark rm(THREAD);
1457   // Return null for arrays and primatives
1458   if (!java_lang_Class::is_primitive(JNIHandles::resolve(cls))) {
1459     klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve(cls));
1460     if (Klass::cast(k)->oop_is_instance()) {
1461       Symbol* sym = instanceKlass::cast(k)->generic_signature();
1462       if (sym == NULL) return NULL;
1463       Handle str = java_lang_String::create_from_symbol(sym, CHECK_NULL);
1464       return (jstring) JNIHandles::make_local(env, str());
1465     }
1466   }
1467   return NULL;
1468 JVM_END
1469 
1470 
1471 JVM_ENTRY(jbyteArray, JVM_GetClassAnnotations(JNIEnv *env, jclass cls))
1472   assert (cls != NULL, "illegal class");
1473   JVMWrapper("JVM_GetClassAnnotations");
1474   ResourceMark rm(THREAD);
1475   // Return null for arrays and primitives
1476   if (!java_lang_Class::is_primitive(JNIHandles::resolve(cls))) {
1477     klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve(cls));
1478     if (Klass::cast(k)->oop_is_instance()) {
1479       return (jbyteArray) JNIHandles::make_local(env,
1480                                   instanceKlass::cast(k)->class_annotations());
1481     }
1482   }
1483   return NULL;
1484 JVM_END
1485 
1486 
1487 JVM_ENTRY(jbyteArray, JVM_GetFieldAnnotations(JNIEnv *env, jobject field))
1488   assert(field != NULL, "illegal field");
1489   JVMWrapper("JVM_GetFieldAnnotations");
1490 
1491   // some of this code was adapted from from jni_FromReflectedField
1492 
1493   // field is a handle to a java.lang.reflect.Field object
1494   oop reflected = JNIHandles::resolve_non_null(field);
1495   oop mirror    = java_lang_reflect_Field::clazz(reflected);
1496   klassOop k    = java_lang_Class::as_klassOop(mirror);
1497   int slot      = java_lang_reflect_Field::slot(reflected);
1498   int modifiers = java_lang_reflect_Field::modifiers(reflected);
1499 
1500   fieldDescriptor fd;
1501   KlassHandle kh(THREAD, k);
1502   intptr_t offset = instanceKlass::cast(kh())->field_offset(slot);
1503 
1504   if (modifiers & JVM_ACC_STATIC) {
1505     // for static fields we only look in the current class
1506     if (!instanceKlass::cast(kh())->find_local_field_from_offset(offset,
1507                                                                  true, &fd)) {
1508       assert(false, "cannot find static field");
1509       return NULL;  // robustness
1510     }
1511   } else {
1512     // for instance fields we start with the current class and work
1513     // our way up through the superclass chain
1514     if (!instanceKlass::cast(kh())->find_field_from_offset(offset, false,
1515                                                            &fd)) {
1516       assert(false, "cannot find instance field");
1517       return NULL;  // robustness
1518     }
1519   }
1520 
1521   return (jbyteArray) JNIHandles::make_local(env, fd.annotations());
1522 JVM_END
1523 
1524 
1525 static methodOop jvm_get_method_common(jobject method, TRAPS) {
1526   // some of this code was adapted from from jni_FromReflectedMethod
1527 
1528   oop reflected = JNIHandles::resolve_non_null(method);
1529   oop mirror    = NULL;
1530   int slot      = 0;
1531 
1532   if (reflected->klass() == SystemDictionary::reflect_Constructor_klass()) {
1533     mirror = java_lang_reflect_Constructor::clazz(reflected);
1534     slot   = java_lang_reflect_Constructor::slot(reflected);
1535   } else {
1536     assert(reflected->klass() == SystemDictionary::reflect_Method_klass(),
1537            "wrong type");
1538     mirror = java_lang_reflect_Method::clazz(reflected);
1539     slot   = java_lang_reflect_Method::slot(reflected);
1540   }
1541   klassOop k = java_lang_Class::as_klassOop(mirror);
1542 
1543   KlassHandle kh(THREAD, k);
1544   methodOop m = instanceKlass::cast(kh())->method_with_idnum(slot);
1545   if (m == NULL) {
1546     assert(false, "cannot find method");
1547     return NULL;  // robustness
1548   }
1549 
1550   return m;
1551 }
1552 
1553 
1554 JVM_ENTRY(jbyteArray, JVM_GetMethodAnnotations(JNIEnv *env, jobject method))
1555   JVMWrapper("JVM_GetMethodAnnotations");
1556 
1557   // method is a handle to a java.lang.reflect.Method object
1558   methodOop m = jvm_get_method_common(method, CHECK_NULL);
1559   return (jbyteArray) JNIHandles::make_local(env, m->annotations());
1560 JVM_END
1561 
1562 
1563 JVM_ENTRY(jbyteArray, JVM_GetMethodDefaultAnnotationValue(JNIEnv *env, jobject method))
1564   JVMWrapper("JVM_GetMethodDefaultAnnotationValue");
1565 
1566   // method is a handle to a java.lang.reflect.Method object
1567   methodOop m = jvm_get_method_common(method, CHECK_NULL);
1568   return (jbyteArray) JNIHandles::make_local(env, m->annotation_default());
1569 JVM_END
1570 
1571 
1572 JVM_ENTRY(jbyteArray, JVM_GetMethodParameterAnnotations(JNIEnv *env, jobject method))
1573   JVMWrapper("JVM_GetMethodParameterAnnotations");
1574 
1575   // method is a handle to a java.lang.reflect.Method object
1576   methodOop m = jvm_get_method_common(method, CHECK_NULL);
1577   return (jbyteArray) JNIHandles::make_local(env, m->parameter_annotations());
1578 JVM_END
1579 
1580 
1581 // New (JDK 1.4) reflection implementation /////////////////////////////////////
1582 
1583 JVM_ENTRY(jobjectArray, JVM_GetClassDeclaredFields(JNIEnv *env, jclass ofClass, jboolean publicOnly))
1584 {
1585   JVMWrapper("JVM_GetClassDeclaredFields");
1586   JvmtiVMObjectAllocEventCollector oam;
1587 
1588   // Exclude primitive types and array types
1589   if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(ofClass)) ||
1590       Klass::cast(java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(ofClass)))->oop_is_javaArray()) {
1591     // Return empty array
1592     oop res = oopFactory::new_objArray(SystemDictionary::reflect_Field_klass(), 0, CHECK_NULL);
1593     return (jobjectArray) JNIHandles::make_local(env, res);
1594   }
1595 
1596   instanceKlassHandle k(THREAD, java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(ofClass)));
1597   constantPoolHandle cp(THREAD, k->constants());
1598 
1599   // Ensure class is linked
1600   k->link_class(CHECK_NULL);
1601 
1602   // 4496456 We need to filter out java.lang.Throwable.backtrace
1603   bool skip_backtrace = false;
1604 
1605   // Allocate result
1606   int num_fields;
1607 
1608   if (publicOnly) {
1609     num_fields = 0;
1610     for (JavaFieldStream fs(k()); !fs.done(); fs.next()) {
1611       if (fs.access_flags().is_public()) ++num_fields;
1612     }
1613   } else {
1614     num_fields = k->java_fields_count();
1615 
1616     if (k() == SystemDictionary::Throwable_klass()) {
1617       num_fields--;
1618       skip_backtrace = true;
1619     }
1620   }
1621 
1622   objArrayOop r = oopFactory::new_objArray(SystemDictionary::reflect_Field_klass(), num_fields, CHECK_NULL);
1623   objArrayHandle result (THREAD, r);
1624 
1625   int out_idx = 0;
1626   fieldDescriptor fd;
1627   for (JavaFieldStream fs(k); !fs.done(); fs.next()) {
1628     if (skip_backtrace) {
1629       // 4496456 skip java.lang.Throwable.backtrace
1630       int offset = fs.offset();
1631       if (offset == java_lang_Throwable::get_backtrace_offset()) continue;
1632     }
1633 
1634     if (!publicOnly || fs.access_flags().is_public()) {
1635       fd.initialize(k(), fs.index());
1636       oop field = Reflection::new_field(&fd, UseNewReflection, CHECK_NULL);
1637       result->obj_at_put(out_idx, field);
1638       ++out_idx;
1639     }
1640   }
1641   assert(out_idx == num_fields, "just checking");
1642   return (jobjectArray) JNIHandles::make_local(env, result());
1643 }
1644 JVM_END
1645 
1646 JVM_ENTRY(jobjectArray, JVM_GetClassDeclaredMethods(JNIEnv *env, jclass ofClass, jboolean publicOnly))
1647 {
1648   JVMWrapper("JVM_GetClassDeclaredMethods");
1649   JvmtiVMObjectAllocEventCollector oam;
1650 
1651   // Exclude primitive types and array types
1652   if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(ofClass))
1653       || Klass::cast(java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(ofClass)))->oop_is_javaArray()) {
1654     // Return empty array
1655     oop res = oopFactory::new_objArray(SystemDictionary::reflect_Method_klass(), 0, CHECK_NULL);
1656     return (jobjectArray) JNIHandles::make_local(env, res);
1657   }
1658 
1659   instanceKlassHandle k(THREAD, java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(ofClass)));
1660 
1661   // Ensure class is linked
1662   k->link_class(CHECK_NULL);
1663 
1664   objArrayHandle methods (THREAD, k->methods());
1665   int methods_length = methods->length();
1666   int num_methods = 0;
1667 
1668   int i;
1669   for (i = 0; i < methods_length; i++) {
1670     methodHandle method(THREAD, (methodOop) methods->obj_at(i));
1671     if (!method->is_initializer()) {
1672       if (!publicOnly || method->is_public()) {
1673         ++num_methods;
1674       }
1675     }
1676   }
1677 
1678   // Allocate result
1679   objArrayOop r = oopFactory::new_objArray(SystemDictionary::reflect_Method_klass(), num_methods, CHECK_NULL);
1680   objArrayHandle result (THREAD, r);
1681 
1682   int out_idx = 0;
1683   for (i = 0; i < methods_length; i++) {
1684     methodHandle method(THREAD, (methodOop) methods->obj_at(i));
1685     if (!method->is_initializer()) {
1686       if (!publicOnly || method->is_public()) {
1687         oop m = Reflection::new_method(method, UseNewReflection, false, CHECK_NULL);
1688         result->obj_at_put(out_idx, m);
1689         ++out_idx;
1690       }
1691     }
1692   }
1693   assert(out_idx == num_methods, "just checking");
1694   return (jobjectArray) JNIHandles::make_local(env, result());
1695 }
1696 JVM_END
1697 
1698 JVM_ENTRY(jobjectArray, JVM_GetClassDeclaredConstructors(JNIEnv *env, jclass ofClass, jboolean publicOnly))
1699 {
1700   JVMWrapper("JVM_GetClassDeclaredConstructors");
1701   JvmtiVMObjectAllocEventCollector oam;
1702 
1703   // Exclude primitive types and array types
1704   if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(ofClass))
1705       || Klass::cast(java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(ofClass)))->oop_is_javaArray()) {
1706     // Return empty array
1707     oop res = oopFactory::new_objArray(SystemDictionary::reflect_Constructor_klass(), 0 , CHECK_NULL);
1708     return (jobjectArray) JNIHandles::make_local(env, res);
1709   }
1710 
1711   instanceKlassHandle k(THREAD, java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(ofClass)));
1712 
1713   // Ensure class is linked
1714   k->link_class(CHECK_NULL);
1715 
1716   objArrayHandle methods (THREAD, k->methods());
1717   int methods_length = methods->length();
1718   int num_constructors = 0;
1719 
1720   int i;
1721   for (i = 0; i < methods_length; i++) {
1722     methodHandle method(THREAD, (methodOop) methods->obj_at(i));
1723     if (method->is_initializer() && !method->is_static()) {
1724       if (!publicOnly || method->is_public()) {
1725         ++num_constructors;
1726       }
1727     }
1728   }
1729 
1730   // Allocate result
1731   objArrayOop r = oopFactory::new_objArray(SystemDictionary::reflect_Constructor_klass(), num_constructors, CHECK_NULL);
1732   objArrayHandle result(THREAD, r);
1733 
1734   int out_idx = 0;
1735   for (i = 0; i < methods_length; i++) {
1736     methodHandle method(THREAD, (methodOop) methods->obj_at(i));
1737     if (method->is_initializer() && !method->is_static()) {
1738       if (!publicOnly || method->is_public()) {
1739         oop m = Reflection::new_constructor(method, CHECK_NULL);
1740         result->obj_at_put(out_idx, m);
1741         ++out_idx;
1742       }
1743     }
1744   }
1745   assert(out_idx == num_constructors, "just checking");
1746   return (jobjectArray) JNIHandles::make_local(env, result());
1747 }
1748 JVM_END
1749 
1750 JVM_ENTRY(jint, JVM_GetClassAccessFlags(JNIEnv *env, jclass cls))
1751 {
1752   JVMWrapper("JVM_GetClassAccessFlags");
1753   if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(cls))) {
1754     // Primitive type
1755     return JVM_ACC_ABSTRACT | JVM_ACC_FINAL | JVM_ACC_PUBLIC;
1756   }
1757 
1758   Klass* k = Klass::cast(java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls)));
1759   return k->access_flags().as_int() & JVM_ACC_WRITTEN_FLAGS;
1760 }
1761 JVM_END
1762 
1763 
1764 // Constant pool access //////////////////////////////////////////////////////////
1765 
1766 JVM_ENTRY(jobject, JVM_GetClassConstantPool(JNIEnv *env, jclass cls))
1767 {
1768   JVMWrapper("JVM_GetClassConstantPool");
1769   JvmtiVMObjectAllocEventCollector oam;
1770 
1771   // Return null for primitives and arrays
1772   if (!java_lang_Class::is_primitive(JNIHandles::resolve_non_null(cls))) {
1773     klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls));
1774     if (Klass::cast(k)->oop_is_instance()) {
1775       instanceKlassHandle k_h(THREAD, k);
1776       Handle jcp = sun_reflect_ConstantPool::create(CHECK_NULL);
1777       sun_reflect_ConstantPool::set_cp_oop(jcp(), k_h->constants());
1778       return JNIHandles::make_local(jcp());
1779     }
1780   }
1781   return NULL;
1782 }
1783 JVM_END
1784 
1785 
1786 JVM_ENTRY(jint, JVM_ConstantPoolGetSize(JNIEnv *env, jobject unused, jobject jcpool))
1787 {
1788   JVMWrapper("JVM_ConstantPoolGetSize");
1789   constantPoolHandle cp = constantPoolHandle(THREAD, constantPoolOop(JNIHandles::resolve_non_null(jcpool)));
1790   return cp->length();
1791 }
1792 JVM_END
1793 
1794 
1795 static void bounds_check(constantPoolHandle cp, jint index, TRAPS) {
1796   if (!cp->is_within_bounds(index)) {
1797     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "Constant pool index out of bounds");
1798   }
1799 }
1800 
1801 
1802 JVM_ENTRY(jclass, JVM_ConstantPoolGetClassAt(JNIEnv *env, jobject unused, jobject jcpool, jint index))
1803 {
1804   JVMWrapper("JVM_ConstantPoolGetClassAt");
1805   constantPoolHandle cp = constantPoolHandle(THREAD, constantPoolOop(JNIHandles::resolve_non_null(jcpool)));
1806   bounds_check(cp, index, CHECK_NULL);
1807   constantTag tag = cp->tag_at(index);
1808   if (!tag.is_klass() && !tag.is_unresolved_klass()) {
1809     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
1810   }
1811   klassOop k = cp->klass_at(index, CHECK_NULL);
1812   return (jclass) JNIHandles::make_local(k->java_mirror());
1813 }
1814 JVM_END
1815 
1816 
1817 JVM_ENTRY(jclass, JVM_ConstantPoolGetClassAtIfLoaded(JNIEnv *env, jobject unused, jobject jcpool, jint index))
1818 {
1819   JVMWrapper("JVM_ConstantPoolGetClassAtIfLoaded");
1820   constantPoolHandle cp = constantPoolHandle(THREAD, constantPoolOop(JNIHandles::resolve_non_null(jcpool)));
1821   bounds_check(cp, index, CHECK_NULL);
1822   constantTag tag = cp->tag_at(index);
1823   if (!tag.is_klass() && !tag.is_unresolved_klass()) {
1824     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
1825   }
1826   klassOop k = constantPoolOopDesc::klass_at_if_loaded(cp, index);
1827   if (k == NULL) return NULL;
1828   return (jclass) JNIHandles::make_local(k->java_mirror());
1829 }
1830 JVM_END
1831 
1832 static jobject get_method_at_helper(constantPoolHandle cp, jint index, bool force_resolution, TRAPS) {
1833   constantTag tag = cp->tag_at(index);
1834   if (!tag.is_method() && !tag.is_interface_method()) {
1835     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
1836   }
1837   int klass_ref  = cp->uncached_klass_ref_index_at(index);
1838   klassOop k_o;
1839   if (force_resolution) {
1840     k_o = cp->klass_at(klass_ref, CHECK_NULL);
1841   } else {
1842     k_o = constantPoolOopDesc::klass_at_if_loaded(cp, klass_ref);
1843     if (k_o == NULL) return NULL;
1844   }
1845   instanceKlassHandle k(THREAD, k_o);
1846   Symbol* name = cp->uncached_name_ref_at(index);
1847   Symbol* sig  = cp->uncached_signature_ref_at(index);
1848   methodHandle m (THREAD, k->find_method(name, sig));
1849   if (m.is_null()) {
1850     THROW_MSG_0(vmSymbols::java_lang_RuntimeException(), "Unable to look up method in target class");
1851   }
1852   oop method;
1853   if (!m->is_initializer() || m->is_static()) {
1854     method = Reflection::new_method(m, true, true, CHECK_NULL);
1855   } else {
1856     method = Reflection::new_constructor(m, CHECK_NULL);
1857   }
1858   return JNIHandles::make_local(method);
1859 }
1860 
1861 JVM_ENTRY(jobject, JVM_ConstantPoolGetMethodAt(JNIEnv *env, jobject unused, jobject jcpool, jint index))
1862 {
1863   JVMWrapper("JVM_ConstantPoolGetMethodAt");
1864   JvmtiVMObjectAllocEventCollector oam;
1865   constantPoolHandle cp = constantPoolHandle(THREAD, constantPoolOop(JNIHandles::resolve_non_null(jcpool)));
1866   bounds_check(cp, index, CHECK_NULL);
1867   jobject res = get_method_at_helper(cp, index, true, CHECK_NULL);
1868   return res;
1869 }
1870 JVM_END
1871 
1872 JVM_ENTRY(jobject, JVM_ConstantPoolGetMethodAtIfLoaded(JNIEnv *env, jobject unused, jobject jcpool, jint index))
1873 {
1874   JVMWrapper("JVM_ConstantPoolGetMethodAtIfLoaded");
1875   JvmtiVMObjectAllocEventCollector oam;
1876   constantPoolHandle cp = constantPoolHandle(THREAD, constantPoolOop(JNIHandles::resolve_non_null(jcpool)));
1877   bounds_check(cp, index, CHECK_NULL);
1878   jobject res = get_method_at_helper(cp, index, false, CHECK_NULL);
1879   return res;
1880 }
1881 JVM_END
1882 
1883 static jobject get_field_at_helper(constantPoolHandle cp, jint index, bool force_resolution, TRAPS) {
1884   constantTag tag = cp->tag_at(index);
1885   if (!tag.is_field()) {
1886     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
1887   }
1888   int klass_ref  = cp->uncached_klass_ref_index_at(index);
1889   klassOop k_o;
1890   if (force_resolution) {
1891     k_o = cp->klass_at(klass_ref, CHECK_NULL);
1892   } else {
1893     k_o = constantPoolOopDesc::klass_at_if_loaded(cp, klass_ref);
1894     if (k_o == NULL) return NULL;
1895   }
1896   instanceKlassHandle k(THREAD, k_o);
1897   Symbol* name = cp->uncached_name_ref_at(index);
1898   Symbol* sig  = cp->uncached_signature_ref_at(index);
1899   fieldDescriptor fd;
1900   klassOop target_klass = k->find_field(name, sig, &fd);
1901   if (target_klass == NULL) {
1902     THROW_MSG_0(vmSymbols::java_lang_RuntimeException(), "Unable to look up field in target class");
1903   }
1904   oop field = Reflection::new_field(&fd, true, CHECK_NULL);
1905   return JNIHandles::make_local(field);
1906 }
1907 
1908 JVM_ENTRY(jobject, JVM_ConstantPoolGetFieldAt(JNIEnv *env, jobject unused, jobject jcpool, jint index))
1909 {
1910   JVMWrapper("JVM_ConstantPoolGetFieldAt");
1911   JvmtiVMObjectAllocEventCollector oam;
1912   constantPoolHandle cp = constantPoolHandle(THREAD, constantPoolOop(JNIHandles::resolve_non_null(jcpool)));
1913   bounds_check(cp, index, CHECK_NULL);
1914   jobject res = get_field_at_helper(cp, index, true, CHECK_NULL);
1915   return res;
1916 }
1917 JVM_END
1918 
1919 JVM_ENTRY(jobject, JVM_ConstantPoolGetFieldAtIfLoaded(JNIEnv *env, jobject unused, jobject jcpool, jint index))
1920 {
1921   JVMWrapper("JVM_ConstantPoolGetFieldAtIfLoaded");
1922   JvmtiVMObjectAllocEventCollector oam;
1923   constantPoolHandle cp = constantPoolHandle(THREAD, constantPoolOop(JNIHandles::resolve_non_null(jcpool)));
1924   bounds_check(cp, index, CHECK_NULL);
1925   jobject res = get_field_at_helper(cp, index, false, CHECK_NULL);
1926   return res;
1927 }
1928 JVM_END
1929 
1930 JVM_ENTRY(jobjectArray, JVM_ConstantPoolGetMemberRefInfoAt(JNIEnv *env, jobject unused, jobject jcpool, jint index))
1931 {
1932   JVMWrapper("JVM_ConstantPoolGetMemberRefInfoAt");
1933   JvmtiVMObjectAllocEventCollector oam;
1934   constantPoolHandle cp = constantPoolHandle(THREAD, constantPoolOop(JNIHandles::resolve_non_null(jcpool)));
1935   bounds_check(cp, index, CHECK_NULL);
1936   constantTag tag = cp->tag_at(index);
1937   if (!tag.is_field_or_method()) {
1938     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
1939   }
1940   int klass_ref = cp->uncached_klass_ref_index_at(index);
1941   Symbol*  klass_name  = cp->klass_name_at(klass_ref);
1942   Symbol*  member_name = cp->uncached_name_ref_at(index);
1943   Symbol*  member_sig  = cp->uncached_signature_ref_at(index);
1944   objArrayOop  dest_o = oopFactory::new_objArray(SystemDictionary::String_klass(), 3, CHECK_NULL);
1945   objArrayHandle dest(THREAD, dest_o);
1946   Handle str = java_lang_String::create_from_symbol(klass_name, CHECK_NULL);
1947   dest->obj_at_put(0, str());
1948   str = java_lang_String::create_from_symbol(member_name, CHECK_NULL);
1949   dest->obj_at_put(1, str());
1950   str = java_lang_String::create_from_symbol(member_sig, CHECK_NULL);
1951   dest->obj_at_put(2, str());
1952   return (jobjectArray) JNIHandles::make_local(dest());
1953 }
1954 JVM_END
1955 
1956 JVM_ENTRY(jint, JVM_ConstantPoolGetIntAt(JNIEnv *env, jobject unused, jobject jcpool, jint index))
1957 {
1958   JVMWrapper("JVM_ConstantPoolGetIntAt");
1959   constantPoolHandle cp = constantPoolHandle(THREAD, constantPoolOop(JNIHandles::resolve_non_null(jcpool)));
1960   bounds_check(cp, index, CHECK_0);
1961   constantTag tag = cp->tag_at(index);
1962   if (!tag.is_int()) {
1963     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
1964   }
1965   return cp->int_at(index);
1966 }
1967 JVM_END
1968 
1969 JVM_ENTRY(jlong, JVM_ConstantPoolGetLongAt(JNIEnv *env, jobject unused, jobject jcpool, jint index))
1970 {
1971   JVMWrapper("JVM_ConstantPoolGetLongAt");
1972   constantPoolHandle cp = constantPoolHandle(THREAD, constantPoolOop(JNIHandles::resolve_non_null(jcpool)));
1973   bounds_check(cp, index, CHECK_(0L));
1974   constantTag tag = cp->tag_at(index);
1975   if (!tag.is_long()) {
1976     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
1977   }
1978   return cp->long_at(index);
1979 }
1980 JVM_END
1981 
1982 JVM_ENTRY(jfloat, JVM_ConstantPoolGetFloatAt(JNIEnv *env, jobject unused, jobject jcpool, jint index))
1983 {
1984   JVMWrapper("JVM_ConstantPoolGetFloatAt");
1985   constantPoolHandle cp = constantPoolHandle(THREAD, constantPoolOop(JNIHandles::resolve_non_null(jcpool)));
1986   bounds_check(cp, index, CHECK_(0.0f));
1987   constantTag tag = cp->tag_at(index);
1988   if (!tag.is_float()) {
1989     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
1990   }
1991   return cp->float_at(index);
1992 }
1993 JVM_END
1994 
1995 JVM_ENTRY(jdouble, JVM_ConstantPoolGetDoubleAt(JNIEnv *env, jobject unused, jobject jcpool, jint index))
1996 {
1997   JVMWrapper("JVM_ConstantPoolGetDoubleAt");
1998   constantPoolHandle cp = constantPoolHandle(THREAD, constantPoolOop(JNIHandles::resolve_non_null(jcpool)));
1999   bounds_check(cp, index, CHECK_(0.0));
2000   constantTag tag = cp->tag_at(index);
2001   if (!tag.is_double()) {
2002     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2003   }
2004   return cp->double_at(index);
2005 }
2006 JVM_END
2007 
2008 JVM_ENTRY(jstring, JVM_ConstantPoolGetStringAt(JNIEnv *env, jobject unused, jobject jcpool, jint index))
2009 {
2010   JVMWrapper("JVM_ConstantPoolGetStringAt");
2011   constantPoolHandle cp = constantPoolHandle(THREAD, constantPoolOop(JNIHandles::resolve_non_null(jcpool)));
2012   bounds_check(cp, index, CHECK_NULL);
2013   constantTag tag = cp->tag_at(index);
2014   if (!tag.is_string() && !tag.is_unresolved_string()) {
2015     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2016   }
2017   oop str = cp->string_at(index, CHECK_NULL);
2018   return (jstring) JNIHandles::make_local(str);
2019 }
2020 JVM_END
2021 
2022 JVM_ENTRY(jstring, JVM_ConstantPoolGetUTF8At(JNIEnv *env, jobject unused, jobject jcpool, jint index))
2023 {
2024   JVMWrapper("JVM_ConstantPoolGetUTF8At");
2025   JvmtiVMObjectAllocEventCollector oam;
2026   constantPoolHandle cp = constantPoolHandle(THREAD, constantPoolOop(JNIHandles::resolve_non_null(jcpool)));
2027   bounds_check(cp, index, CHECK_NULL);
2028   constantTag tag = cp->tag_at(index);
2029   if (!tag.is_symbol()) {
2030     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2031   }
2032   Symbol* sym = cp->symbol_at(index);
2033   Handle str = java_lang_String::create_from_symbol(sym, CHECK_NULL);
2034   return (jstring) JNIHandles::make_local(str());
2035 }
2036 JVM_END
2037 
2038 
2039 // Assertion support. //////////////////////////////////////////////////////////
2040 
2041 JVM_ENTRY(jboolean, JVM_DesiredAssertionStatus(JNIEnv *env, jclass unused, jclass cls))
2042   JVMWrapper("JVM_DesiredAssertionStatus");
2043   assert(cls != NULL, "bad class");
2044 
2045   oop r = JNIHandles::resolve(cls);
2046   assert(! java_lang_Class::is_primitive(r), "primitive classes not allowed");
2047   if (java_lang_Class::is_primitive(r)) return false;
2048 
2049   klassOop k = java_lang_Class::as_klassOop(r);
2050   assert(Klass::cast(k)->oop_is_instance(), "must be an instance klass");
2051   if (! Klass::cast(k)->oop_is_instance()) return false;
2052 
2053   ResourceMark rm(THREAD);
2054   const char* name = Klass::cast(k)->name()->as_C_string();
2055   bool system_class = Klass::cast(k)->class_loader() == NULL;
2056   return JavaAssertions::enabled(name, system_class);
2057 
2058 JVM_END
2059 
2060 
2061 // Return a new AssertionStatusDirectives object with the fields filled in with
2062 // command-line assertion arguments (i.e., -ea, -da).
2063 JVM_ENTRY(jobject, JVM_AssertionStatusDirectives(JNIEnv *env, jclass unused))
2064   JVMWrapper("JVM_AssertionStatusDirectives");
2065   JvmtiVMObjectAllocEventCollector oam;
2066   oop asd = JavaAssertions::createAssertionStatusDirectives(CHECK_NULL);
2067   return JNIHandles::make_local(env, asd);
2068 JVM_END
2069 
2070 // Verification ////////////////////////////////////////////////////////////////////////////////
2071 
2072 // Reflection for the verifier /////////////////////////////////////////////////////////////////
2073 
2074 // RedefineClasses support: bug 6214132 caused verification to fail.
2075 // All functions from this section should call the jvmtiThreadSate function:
2076 //   klassOop class_to_verify_considering_redefinition(klassOop klass).
2077 // The function returns a klassOop of the _scratch_class if the verifier
2078 // was invoked in the middle of the class redefinition.
2079 // Otherwise it returns its argument value which is the _the_class klassOop.
2080 // Please, refer to the description in the jvmtiThreadSate.hpp.
2081 
2082 JVM_ENTRY(const char*, JVM_GetClassNameUTF(JNIEnv *env, jclass cls))
2083   JVMWrapper("JVM_GetClassNameUTF");
2084   klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls));
2085   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2086   return Klass::cast(k)->name()->as_utf8();
2087 JVM_END
2088 
2089 
2090 JVM_QUICK_ENTRY(void, JVM_GetClassCPTypes(JNIEnv *env, jclass cls, unsigned char *types))
2091   JVMWrapper("JVM_GetClassCPTypes");
2092   klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls));
2093   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2094   // types will have length zero if this is not an instanceKlass
2095   // (length is determined by call to JVM_GetClassCPEntriesCount)
2096   if (Klass::cast(k)->oop_is_instance()) {
2097     constantPoolOop cp = instanceKlass::cast(k)->constants();
2098     for (int index = cp->length() - 1; index >= 0; index--) {
2099       constantTag tag = cp->tag_at(index);
2100       types[index] = (tag.is_unresolved_klass()) ? JVM_CONSTANT_Class :
2101                      (tag.is_unresolved_string()) ? JVM_CONSTANT_String : tag.value();
2102   }
2103   }
2104 JVM_END
2105 
2106 
2107 JVM_QUICK_ENTRY(jint, JVM_GetClassCPEntriesCount(JNIEnv *env, jclass cls))
2108   JVMWrapper("JVM_GetClassCPEntriesCount");
2109   klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls));
2110   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2111   if (!Klass::cast(k)->oop_is_instance())
2112     return 0;
2113   return instanceKlass::cast(k)->constants()->length();
2114 JVM_END
2115 
2116 
2117 JVM_QUICK_ENTRY(jint, JVM_GetClassFieldsCount(JNIEnv *env, jclass cls))
2118   JVMWrapper("JVM_GetClassFieldsCount");
2119   klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls));
2120   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2121   if (!Klass::cast(k)->oop_is_instance())
2122     return 0;
2123   return instanceKlass::cast(k)->java_fields_count();
2124 JVM_END
2125 
2126 
2127 JVM_QUICK_ENTRY(jint, JVM_GetClassMethodsCount(JNIEnv *env, jclass cls))
2128   JVMWrapper("JVM_GetClassMethodsCount");
2129   klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls));
2130   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2131   if (!Klass::cast(k)->oop_is_instance())
2132     return 0;
2133   return instanceKlass::cast(k)->methods()->length();
2134 JVM_END
2135 
2136 
2137 // The following methods, used for the verifier, are never called with
2138 // array klasses, so a direct cast to instanceKlass is safe.
2139 // Typically, these methods are called in a loop with bounds determined
2140 // by the results of JVM_GetClass{Fields,Methods}Count, which return
2141 // zero for arrays.
2142 JVM_QUICK_ENTRY(void, JVM_GetMethodIxExceptionIndexes(JNIEnv *env, jclass cls, jint method_index, unsigned short *exceptions))
2143   JVMWrapper("JVM_GetMethodIxExceptionIndexes");
2144   klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls));
2145   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2146   oop method = instanceKlass::cast(k)->methods()->obj_at(method_index);
2147   int length = methodOop(method)->checked_exceptions_length();
2148   if (length > 0) {
2149     CheckedExceptionElement* table= methodOop(method)->checked_exceptions_start();
2150     for (int i = 0; i < length; i++) {
2151       exceptions[i] = table[i].class_cp_index;
2152     }
2153   }
2154 JVM_END
2155 
2156 
2157 JVM_QUICK_ENTRY(jint, JVM_GetMethodIxExceptionsCount(JNIEnv *env, jclass cls, jint method_index))
2158   JVMWrapper("JVM_GetMethodIxExceptionsCount");
2159   klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls));
2160   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2161   oop method = instanceKlass::cast(k)->methods()->obj_at(method_index);
2162   return methodOop(method)->checked_exceptions_length();
2163 JVM_END
2164 
2165 
2166 JVM_QUICK_ENTRY(void, JVM_GetMethodIxByteCode(JNIEnv *env, jclass cls, jint method_index, unsigned char *code))
2167   JVMWrapper("JVM_GetMethodIxByteCode");
2168   klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls));
2169   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2170   oop method = instanceKlass::cast(k)->methods()->obj_at(method_index);
2171   memcpy(code, methodOop(method)->code_base(), methodOop(method)->code_size());
2172 JVM_END
2173 
2174 
2175 JVM_QUICK_ENTRY(jint, JVM_GetMethodIxByteCodeLength(JNIEnv *env, jclass cls, jint method_index))
2176   JVMWrapper("JVM_GetMethodIxByteCodeLength");
2177   klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls));
2178   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2179   oop method = instanceKlass::cast(k)->methods()->obj_at(method_index);
2180   return methodOop(method)->code_size();
2181 JVM_END
2182 
2183 
2184 JVM_QUICK_ENTRY(void, JVM_GetMethodIxExceptionTableEntry(JNIEnv *env, jclass cls, jint method_index, jint entry_index, JVM_ExceptionTableEntryType *entry))
2185   JVMWrapper("JVM_GetMethodIxExceptionTableEntry");
2186   klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls));
2187   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2188   oop method = instanceKlass::cast(k)->methods()->obj_at(method_index);
2189   typeArrayOop extable = methodOop(method)->exception_table();
2190   entry->start_pc   = extable->int_at(entry_index * 4);
2191   entry->end_pc     = extable->int_at(entry_index * 4 + 1);
2192   entry->handler_pc = extable->int_at(entry_index * 4 + 2);
2193   entry->catchType  = extable->int_at(entry_index * 4 + 3);
2194 JVM_END
2195 
2196 
2197 JVM_QUICK_ENTRY(jint, JVM_GetMethodIxExceptionTableLength(JNIEnv *env, jclass cls, int method_index))
2198   JVMWrapper("JVM_GetMethodIxExceptionTableLength");
2199   klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls));
2200   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2201   oop method = instanceKlass::cast(k)->methods()->obj_at(method_index);
2202   return methodOop(method)->exception_table()->length() / 4;
2203 JVM_END
2204 
2205 
2206 JVM_QUICK_ENTRY(jint, JVM_GetMethodIxModifiers(JNIEnv *env, jclass cls, int method_index))
2207   JVMWrapper("JVM_GetMethodIxModifiers");
2208   klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls));
2209   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2210   oop method = instanceKlass::cast(k)->methods()->obj_at(method_index);
2211   return methodOop(method)->access_flags().as_int() & JVM_RECOGNIZED_METHOD_MODIFIERS;
2212 JVM_END
2213 
2214 
2215 JVM_QUICK_ENTRY(jint, JVM_GetFieldIxModifiers(JNIEnv *env, jclass cls, int field_index))
2216   JVMWrapper("JVM_GetFieldIxModifiers");
2217   klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls));
2218   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2219   return instanceKlass::cast(k)->field_access_flags(field_index) & JVM_RECOGNIZED_FIELD_MODIFIERS;
2220 JVM_END
2221 
2222 
2223 JVM_QUICK_ENTRY(jint, JVM_GetMethodIxLocalsCount(JNIEnv *env, jclass cls, int method_index))
2224   JVMWrapper("JVM_GetMethodIxLocalsCount");
2225   klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls));
2226   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2227   oop method = instanceKlass::cast(k)->methods()->obj_at(method_index);
2228   return methodOop(method)->max_locals();
2229 JVM_END
2230 
2231 
2232 JVM_QUICK_ENTRY(jint, JVM_GetMethodIxArgsSize(JNIEnv *env, jclass cls, int method_index))
2233   JVMWrapper("JVM_GetMethodIxArgsSize");
2234   klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls));
2235   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2236   oop method = instanceKlass::cast(k)->methods()->obj_at(method_index);
2237   return methodOop(method)->size_of_parameters();
2238 JVM_END
2239 
2240 
2241 JVM_QUICK_ENTRY(jint, JVM_GetMethodIxMaxStack(JNIEnv *env, jclass cls, int method_index))
2242   JVMWrapper("JVM_GetMethodIxMaxStack");
2243   klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls));
2244   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2245   oop method = instanceKlass::cast(k)->methods()->obj_at(method_index);
2246   return methodOop(method)->max_stack();
2247 JVM_END
2248 
2249 
2250 JVM_QUICK_ENTRY(jboolean, JVM_IsConstructorIx(JNIEnv *env, jclass cls, int method_index))
2251   JVMWrapper("JVM_IsConstructorIx");
2252   ResourceMark rm(THREAD);
2253   klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls));
2254   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2255   oop method = instanceKlass::cast(k)->methods()->obj_at(method_index);
2256   return methodOop(method)->name() == vmSymbols::object_initializer_name();
2257 JVM_END
2258 
2259 
2260 JVM_ENTRY(const char*, JVM_GetMethodIxNameUTF(JNIEnv *env, jclass cls, jint method_index))
2261   JVMWrapper("JVM_GetMethodIxIxUTF");
2262   klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls));
2263   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2264   oop method = instanceKlass::cast(k)->methods()->obj_at(method_index);
2265   return methodOop(method)->name()->as_utf8();
2266 JVM_END
2267 
2268 
2269 JVM_ENTRY(const char*, JVM_GetMethodIxSignatureUTF(JNIEnv *env, jclass cls, jint method_index))
2270   JVMWrapper("JVM_GetMethodIxSignatureUTF");
2271   klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls));
2272   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2273   oop method = instanceKlass::cast(k)->methods()->obj_at(method_index);
2274   return methodOop(method)->signature()->as_utf8();
2275 JVM_END
2276 
2277 /**
2278  * All of these JVM_GetCP-xxx methods are used by the old verifier to
2279  * read entries in the constant pool.  Since the old verifier always
2280  * works on a copy of the code, it will not see any rewriting that
2281  * may possibly occur in the middle of verification.  So it is important
2282  * that nothing it calls tries to use the cpCache instead of the raw
2283  * constant pool, so we must use cp->uncached_x methods when appropriate.
2284  */
2285 JVM_ENTRY(const char*, JVM_GetCPFieldNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2286   JVMWrapper("JVM_GetCPFieldNameUTF");
2287   klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls));
2288   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2289   constantPoolOop cp = instanceKlass::cast(k)->constants();
2290   switch (cp->tag_at(cp_index).value()) {
2291     case JVM_CONSTANT_Fieldref:
2292       return cp->uncached_name_ref_at(cp_index)->as_utf8();
2293     default:
2294       fatal("JVM_GetCPFieldNameUTF: illegal constant");
2295   }
2296   ShouldNotReachHere();
2297   return NULL;
2298 JVM_END
2299 
2300 
2301 JVM_ENTRY(const char*, JVM_GetCPMethodNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2302   JVMWrapper("JVM_GetCPMethodNameUTF");
2303   klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls));
2304   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2305   constantPoolOop cp = instanceKlass::cast(k)->constants();
2306   switch (cp->tag_at(cp_index).value()) {
2307     case JVM_CONSTANT_InterfaceMethodref:
2308     case JVM_CONSTANT_Methodref:
2309     case JVM_CONSTANT_NameAndType:  // for invokedynamic
2310       return cp->uncached_name_ref_at(cp_index)->as_utf8();
2311     default:
2312       fatal("JVM_GetCPMethodNameUTF: illegal constant");
2313   }
2314   ShouldNotReachHere();
2315   return NULL;
2316 JVM_END
2317 
2318 
2319 JVM_ENTRY(const char*, JVM_GetCPMethodSignatureUTF(JNIEnv *env, jclass cls, jint cp_index))
2320   JVMWrapper("JVM_GetCPMethodSignatureUTF");
2321   klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls));
2322   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2323   constantPoolOop cp = instanceKlass::cast(k)->constants();
2324   switch (cp->tag_at(cp_index).value()) {
2325     case JVM_CONSTANT_InterfaceMethodref:
2326     case JVM_CONSTANT_Methodref:
2327     case JVM_CONSTANT_NameAndType:  // for invokedynamic
2328       return cp->uncached_signature_ref_at(cp_index)->as_utf8();
2329     default:
2330       fatal("JVM_GetCPMethodSignatureUTF: illegal constant");
2331   }
2332   ShouldNotReachHere();
2333   return NULL;
2334 JVM_END
2335 
2336 
2337 JVM_ENTRY(const char*, JVM_GetCPFieldSignatureUTF(JNIEnv *env, jclass cls, jint cp_index))
2338   JVMWrapper("JVM_GetCPFieldSignatureUTF");
2339   klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls));
2340   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2341   constantPoolOop cp = instanceKlass::cast(k)->constants();
2342   switch (cp->tag_at(cp_index).value()) {
2343     case JVM_CONSTANT_Fieldref:
2344       return cp->uncached_signature_ref_at(cp_index)->as_utf8();
2345     default:
2346       fatal("JVM_GetCPFieldSignatureUTF: illegal constant");
2347   }
2348   ShouldNotReachHere();
2349   return NULL;
2350 JVM_END
2351 
2352 
2353 JVM_ENTRY(const char*, JVM_GetCPClassNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2354   JVMWrapper("JVM_GetCPClassNameUTF");
2355   klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls));
2356   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2357   constantPoolOop cp = instanceKlass::cast(k)->constants();
2358   Symbol* classname = cp->klass_name_at(cp_index);
2359   return classname->as_utf8();
2360 JVM_END
2361 
2362 
2363 JVM_ENTRY(const char*, JVM_GetCPFieldClassNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2364   JVMWrapper("JVM_GetCPFieldClassNameUTF");
2365   klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls));
2366   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2367   constantPoolOop cp = instanceKlass::cast(k)->constants();
2368   switch (cp->tag_at(cp_index).value()) {
2369     case JVM_CONSTANT_Fieldref: {
2370       int class_index = cp->uncached_klass_ref_index_at(cp_index);
2371       Symbol* classname = cp->klass_name_at(class_index);
2372       return classname->as_utf8();
2373     }
2374     default:
2375       fatal("JVM_GetCPFieldClassNameUTF: illegal constant");
2376   }
2377   ShouldNotReachHere();
2378   return NULL;
2379 JVM_END
2380 
2381 
2382 JVM_ENTRY(const char*, JVM_GetCPMethodClassNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2383   JVMWrapper("JVM_GetCPMethodClassNameUTF");
2384   klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls));
2385   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2386   constantPoolOop cp = instanceKlass::cast(k)->constants();
2387   switch (cp->tag_at(cp_index).value()) {
2388     case JVM_CONSTANT_Methodref:
2389     case JVM_CONSTANT_InterfaceMethodref: {
2390       int class_index = cp->uncached_klass_ref_index_at(cp_index);
2391       Symbol* classname = cp->klass_name_at(class_index);
2392       return classname->as_utf8();
2393     }
2394     default:
2395       fatal("JVM_GetCPMethodClassNameUTF: illegal constant");
2396   }
2397   ShouldNotReachHere();
2398   return NULL;
2399 JVM_END
2400 
2401 
2402 JVM_ENTRY(jint, JVM_GetCPFieldModifiers(JNIEnv *env, jclass cls, int cp_index, jclass called_cls))
2403   JVMWrapper("JVM_GetCPFieldModifiers");
2404   klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls));
2405   klassOop k_called = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(called_cls));
2406   k        = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2407   k_called = JvmtiThreadState::class_to_verify_considering_redefinition(k_called, thread);
2408   constantPoolOop cp = instanceKlass::cast(k)->constants();
2409   constantPoolOop cp_called = instanceKlass::cast(k_called)->constants();
2410   switch (cp->tag_at(cp_index).value()) {
2411     case JVM_CONSTANT_Fieldref: {
2412       Symbol* name      = cp->uncached_name_ref_at(cp_index);
2413       Symbol* signature = cp->uncached_signature_ref_at(cp_index);
2414       for (JavaFieldStream fs(k_called); !fs.done(); fs.next()) {
2415         if (fs.name() == name && fs.signature() == signature) {
2416           return fs.access_flags().as_short() & JVM_RECOGNIZED_FIELD_MODIFIERS;
2417         }
2418       }
2419       return -1;
2420     }
2421     default:
2422       fatal("JVM_GetCPFieldModifiers: illegal constant");
2423   }
2424   ShouldNotReachHere();
2425   return 0;
2426 JVM_END
2427 
2428 
2429 JVM_QUICK_ENTRY(jint, JVM_GetCPMethodModifiers(JNIEnv *env, jclass cls, int cp_index, jclass called_cls))
2430   JVMWrapper("JVM_GetCPMethodModifiers");
2431   klassOop k = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(cls));
2432   klassOop k_called = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(called_cls));
2433   k        = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2434   k_called = JvmtiThreadState::class_to_verify_considering_redefinition(k_called, thread);
2435   constantPoolOop cp = instanceKlass::cast(k)->constants();
2436   switch (cp->tag_at(cp_index).value()) {
2437     case JVM_CONSTANT_Methodref:
2438     case JVM_CONSTANT_InterfaceMethodref: {
2439       Symbol* name      = cp->uncached_name_ref_at(cp_index);
2440       Symbol* signature = cp->uncached_signature_ref_at(cp_index);
2441       objArrayOop methods = instanceKlass::cast(k_called)->methods();
2442       int methods_count = methods->length();
2443       for (int i = 0; i < methods_count; i++) {
2444         methodOop method = methodOop(methods->obj_at(i));
2445         if (method->name() == name && method->signature() == signature) {
2446             return method->access_flags().as_int() & JVM_RECOGNIZED_METHOD_MODIFIERS;
2447         }
2448       }
2449       return -1;
2450     }
2451     default:
2452       fatal("JVM_GetCPMethodModifiers: illegal constant");
2453   }
2454   ShouldNotReachHere();
2455   return 0;
2456 JVM_END
2457 
2458 
2459 // Misc //////////////////////////////////////////////////////////////////////////////////////////////
2460 
2461 JVM_LEAF(void, JVM_ReleaseUTF(const char *utf))
2462   // So long as UTF8::convert_to_utf8 returns resource strings, we don't have to do anything
2463 JVM_END
2464 
2465 
2466 JVM_ENTRY(jboolean, JVM_IsSameClassPackage(JNIEnv *env, jclass class1, jclass class2))
2467   JVMWrapper("JVM_IsSameClassPackage");
2468   oop class1_mirror = JNIHandles::resolve_non_null(class1);
2469   oop class2_mirror = JNIHandles::resolve_non_null(class2);
2470   klassOop klass1 = java_lang_Class::as_klassOop(class1_mirror);
2471   klassOop klass2 = java_lang_Class::as_klassOop(class2_mirror);
2472   return (jboolean) Reflection::is_same_class_package(klass1, klass2);
2473 JVM_END
2474 
2475 
2476 // IO functions ////////////////////////////////////////////////////////////////////////////////////////
2477 
2478 JVM_LEAF(jint, JVM_Open(const char *fname, jint flags, jint mode))
2479   JVMWrapper2("JVM_Open (%s)", fname);
2480 
2481   //%note jvm_r6
2482   int result = os::open(fname, flags, mode);
2483   if (result >= 0) {
2484     return result;
2485   } else {
2486     switch(errno) {
2487       case EEXIST:
2488         return JVM_EEXIST;
2489       default:
2490         return -1;
2491     }
2492   }
2493 JVM_END
2494 
2495 
2496 JVM_LEAF(jint, JVM_Close(jint fd))
2497   JVMWrapper2("JVM_Close (0x%x)", fd);
2498   //%note jvm_r6
2499   return os::close(fd);
2500 JVM_END
2501 
2502 
2503 JVM_LEAF(jint, JVM_Read(jint fd, char *buf, jint nbytes))
2504   JVMWrapper2("JVM_Read (0x%x)", fd);
2505 
2506   //%note jvm_r6
2507   return (jint)os::restartable_read(fd, buf, nbytes);
2508 JVM_END
2509 
2510 
2511 JVM_LEAF(jint, JVM_Write(jint fd, char *buf, jint nbytes))
2512   JVMWrapper2("JVM_Write (0x%x)", fd);
2513 
2514   //%note jvm_r6
2515   return (jint)os::write(fd, buf, nbytes);
2516 JVM_END
2517 
2518 
2519 JVM_LEAF(jint, JVM_Available(jint fd, jlong *pbytes))
2520   JVMWrapper2("JVM_Available (0x%x)", fd);
2521   //%note jvm_r6
2522   return os::available(fd, pbytes);
2523 JVM_END
2524 
2525 
2526 JVM_LEAF(jlong, JVM_Lseek(jint fd, jlong offset, jint whence))
2527   JVMWrapper4("JVM_Lseek (0x%x, %Ld, %d)", fd, offset, whence);
2528   //%note jvm_r6
2529   return os::lseek(fd, offset, whence);
2530 JVM_END
2531 
2532 
2533 JVM_LEAF(jint, JVM_SetLength(jint fd, jlong length))
2534   JVMWrapper3("JVM_SetLength (0x%x, %Ld)", fd, length);
2535   return os::ftruncate(fd, length);
2536 JVM_END
2537 
2538 
2539 JVM_LEAF(jint, JVM_Sync(jint fd))
2540   JVMWrapper2("JVM_Sync (0x%x)", fd);
2541   //%note jvm_r6
2542   return os::fsync(fd);
2543 JVM_END
2544 
2545 
2546 // Printing support //////////////////////////////////////////////////
2547 extern "C" {
2548 
2549 int jio_vsnprintf(char *str, size_t count, const char *fmt, va_list args) {
2550   // see bug 4399518, 4417214
2551   if ((intptr_t)count <= 0) return -1;
2552   return vsnprintf(str, count, fmt, args);
2553 }
2554 
2555 
2556 int jio_snprintf(char *str, size_t count, const char *fmt, ...) {
2557   va_list args;
2558   int len;
2559   va_start(args, fmt);
2560   len = jio_vsnprintf(str, count, fmt, args);
2561   va_end(args);
2562   return len;
2563 }
2564 
2565 
2566 int jio_fprintf(FILE* f, const char *fmt, ...) {
2567   int len;
2568   va_list args;
2569   va_start(args, fmt);
2570   len = jio_vfprintf(f, fmt, args);
2571   va_end(args);
2572   return len;
2573 }
2574 
2575 
2576 int jio_vfprintf(FILE* f, const char *fmt, va_list args) {
2577   if (Arguments::vfprintf_hook() != NULL) {
2578      return Arguments::vfprintf_hook()(f, fmt, args);
2579   } else {
2580     return vfprintf(f, fmt, args);
2581   }
2582 }
2583 
2584 
2585 JNIEXPORT int jio_printf(const char *fmt, ...) {
2586   int len;
2587   va_list args;
2588   va_start(args, fmt);
2589   len = jio_vfprintf(defaultStream::output_stream(), fmt, args);
2590   va_end(args);
2591   return len;
2592 }
2593 
2594 
2595 // HotSpot specific jio method
2596 void jio_print(const char* s) {
2597   // Try to make this function as atomic as possible.
2598   if (Arguments::vfprintf_hook() != NULL) {
2599     jio_fprintf(defaultStream::output_stream(), "%s", s);
2600   } else {
2601     // Make an unused local variable to avoid warning from gcc 4.x compiler.
2602     size_t count = ::write(defaultStream::output_fd(), s, (int)strlen(s));
2603   }
2604 }
2605 
2606 } // Extern C
2607 
2608 // java.lang.Thread //////////////////////////////////////////////////////////////////////////////
2609 
2610 // In most of the JVM Thread support functions we need to be sure to lock the Threads_lock
2611 // to prevent the target thread from exiting after we have a pointer to the C++ Thread or
2612 // OSThread objects.  The exception to this rule is when the target object is the thread
2613 // doing the operation, in which case we know that the thread won't exit until the
2614 // operation is done (all exits being voluntary).  There are a few cases where it is
2615 // rather silly to do operations on yourself, like resuming yourself or asking whether
2616 // you are alive.  While these can still happen, they are not subject to deadlocks if
2617 // the lock is held while the operation occurs (this is not the case for suspend, for
2618 // instance), and are very unlikely.  Because IsAlive needs to be fast and its
2619 // implementation is local to this file, we always lock Threads_lock for that one.
2620 
2621 static void thread_entry(JavaThread* thread, TRAPS) {
2622   HandleMark hm(THREAD);
2623   Handle obj(THREAD, thread->threadObj());
2624   JavaValue result(T_VOID);
2625   JavaCalls::call_virtual(&result,
2626                           obj,
2627                           KlassHandle(THREAD, SystemDictionary::Thread_klass()),
2628                           vmSymbols::run_method_name(),
2629                           vmSymbols::void_method_signature(),
2630                           THREAD);
2631 }
2632 
2633 
2634 JVM_ENTRY(void, JVM_StartThread(JNIEnv* env, jobject jthread))
2635   JVMWrapper("JVM_StartThread");
2636   JavaThread *native_thread = NULL;
2637 
2638   // We cannot hold the Threads_lock when we throw an exception,
2639   // due to rank ordering issues. Example:  we might need to grab the
2640   // Heap_lock while we construct the exception.
2641   bool throw_illegal_thread_state = false;
2642 
2643   // We must release the Threads_lock before we can post a jvmti event
2644   // in Thread::start.
2645   {
2646     // Ensure that the C++ Thread and OSThread structures aren't freed before
2647     // we operate.
2648     MutexLocker mu(Threads_lock);
2649 
2650     // Since JDK 5 the java.lang.Thread threadStatus is used to prevent
2651     // re-starting an already started thread, so we should usually find
2652     // that the JavaThread is null. However for a JNI attached thread
2653     // there is a small window between the Thread object being created
2654     // (with its JavaThread set) and the update to its threadStatus, so we
2655     // have to check for this
2656     if (java_lang_Thread::thread(JNIHandles::resolve_non_null(jthread)) != NULL) {
2657       throw_illegal_thread_state = true;
2658     } else {
2659       // We could also check the stillborn flag to see if this thread was already stopped, but
2660       // for historical reasons we let the thread detect that itself when it starts running
2661 
2662       jlong size =
2663              java_lang_Thread::stackSize(JNIHandles::resolve_non_null(jthread));
2664       // Allocate the C++ Thread structure and create the native thread.  The
2665       // stack size retrieved from java is signed, but the constructor takes
2666       // size_t (an unsigned type), so avoid passing negative values which would
2667       // result in really large stacks.
2668       size_t sz = size > 0 ? (size_t) size : 0;
2669       native_thread = new JavaThread(&thread_entry, sz);
2670 
2671       // At this point it may be possible that no osthread was created for the
2672       // JavaThread due to lack of memory. Check for this situation and throw
2673       // an exception if necessary. Eventually we may want to change this so
2674       // that we only grab the lock if the thread was created successfully -
2675       // then we can also do this check and throw the exception in the
2676       // JavaThread constructor.
2677       if (native_thread->osthread() != NULL) {
2678         // Note: the current thread is not being used within "prepare".
2679         native_thread->prepare(jthread);
2680       }
2681     }
2682   }
2683 
2684   if (throw_illegal_thread_state) {
2685     THROW(vmSymbols::java_lang_IllegalThreadStateException());
2686   }
2687 
2688   assert(native_thread != NULL, "Starting null thread?");
2689 
2690   if (native_thread->osthread() == NULL) {
2691     // No one should hold a reference to the 'native_thread'.
2692     delete native_thread;
2693     if (JvmtiExport::should_post_resource_exhausted()) {
2694       JvmtiExport::post_resource_exhausted(
2695         JVMTI_RESOURCE_EXHAUSTED_OOM_ERROR | JVMTI_RESOURCE_EXHAUSTED_THREADS,
2696         "unable to create new native thread");
2697     }
2698     THROW_MSG(vmSymbols::java_lang_OutOfMemoryError(),
2699               "unable to create new native thread");
2700   }
2701 
2702   Thread::start(native_thread);
2703 
2704 JVM_END
2705 
2706 // JVM_Stop is implemented using a VM_Operation, so threads are forced to safepoints
2707 // before the quasi-asynchronous exception is delivered.  This is a little obtrusive,
2708 // but is thought to be reliable and simple. In the case, where the receiver is the
2709 // same thread as the sender, no safepoint is needed.
2710 JVM_ENTRY(void, JVM_StopThread(JNIEnv* env, jobject jthread, jobject throwable))
2711   JVMWrapper("JVM_StopThread");
2712 
2713   oop java_throwable = JNIHandles::resolve(throwable);
2714   if (java_throwable == NULL) {
2715     THROW(vmSymbols::java_lang_NullPointerException());
2716   }
2717   oop java_thread = JNIHandles::resolve_non_null(jthread);
2718   JavaThread* receiver = java_lang_Thread::thread(java_thread);
2719   Events::log_exception(JavaThread::current(),
2720                         "JVM_StopThread thread JavaThread " INTPTR_FORMAT " as oop " INTPTR_FORMAT " [exception " INTPTR_FORMAT "]",
2721                         receiver, (address)java_thread, throwable);
2722   // First check if thread is alive
2723   if (receiver != NULL) {
2724     // Check if exception is getting thrown at self (use oop equality, since the
2725     // target object might exit)
2726     if (java_thread == thread->threadObj()) {
2727       THROW_OOP(java_throwable);
2728     } else {
2729       // Enques a VM_Operation to stop all threads and then deliver the exception...
2730       Thread::send_async_exception(java_thread, JNIHandles::resolve(throwable));
2731     }
2732   }
2733   else {
2734     // Either:
2735     // - target thread has not been started before being stopped, or
2736     // - target thread already terminated
2737     // We could read the threadStatus to determine which case it is
2738     // but that is overkill as it doesn't matter. We must set the
2739     // stillborn flag for the first case, and if the thread has already
2740     // exited setting this flag has no affect
2741     java_lang_Thread::set_stillborn(java_thread);
2742   }
2743 JVM_END
2744 
2745 
2746 JVM_ENTRY(jboolean, JVM_IsThreadAlive(JNIEnv* env, jobject jthread))
2747   JVMWrapper("JVM_IsThreadAlive");
2748 
2749   oop thread_oop = JNIHandles::resolve_non_null(jthread);
2750   return java_lang_Thread::is_alive(thread_oop);
2751 JVM_END
2752 
2753 
2754 JVM_ENTRY(void, JVM_SuspendThread(JNIEnv* env, jobject jthread))
2755   JVMWrapper("JVM_SuspendThread");
2756   oop java_thread = JNIHandles::resolve_non_null(jthread);
2757   JavaThread* receiver = java_lang_Thread::thread(java_thread);
2758 
2759   if (receiver != NULL) {
2760     // thread has run and has not exited (still on threads list)
2761 
2762     {
2763       MutexLockerEx ml(receiver->SR_lock(), Mutex::_no_safepoint_check_flag);
2764       if (receiver->is_external_suspend()) {
2765         // Don't allow nested external suspend requests. We can't return
2766         // an error from this interface so just ignore the problem.
2767         return;
2768       }
2769       if (receiver->is_exiting()) { // thread is in the process of exiting
2770         return;
2771       }
2772       receiver->set_external_suspend();
2773     }
2774 
2775     // java_suspend() will catch threads in the process of exiting
2776     // and will ignore them.
2777     receiver->java_suspend();
2778 
2779     // It would be nice to have the following assertion in all the
2780     // time, but it is possible for a racing resume request to have
2781     // resumed this thread right after we suspended it. Temporarily
2782     // enable this assertion if you are chasing a different kind of
2783     // bug.
2784     //
2785     // assert(java_lang_Thread::thread(receiver->threadObj()) == NULL ||
2786     //   receiver->is_being_ext_suspended(), "thread is not suspended");
2787   }
2788 JVM_END
2789 
2790 
2791 JVM_ENTRY(void, JVM_ResumeThread(JNIEnv* env, jobject jthread))
2792   JVMWrapper("JVM_ResumeThread");
2793   // Ensure that the C++ Thread and OSThread structures aren't freed before we operate.
2794   // We need to *always* get the threads lock here, since this operation cannot be allowed during
2795   // a safepoint. The safepoint code relies on suspending a thread to examine its state. If other
2796   // threads randomly resumes threads, then a thread might not be suspended when the safepoint code
2797   // looks at it.
2798   MutexLocker ml(Threads_lock);
2799   JavaThread* thr = java_lang_Thread::thread(JNIHandles::resolve_non_null(jthread));
2800   if (thr != NULL) {
2801     // the thread has run and is not in the process of exiting
2802     thr->java_resume();
2803   }
2804 JVM_END
2805 
2806 
2807 JVM_ENTRY(void, JVM_SetThreadPriority(JNIEnv* env, jobject jthread, jint prio))
2808   JVMWrapper("JVM_SetThreadPriority");
2809   // Ensure that the C++ Thread and OSThread structures aren't freed before we operate
2810   MutexLocker ml(Threads_lock);
2811   oop java_thread = JNIHandles::resolve_non_null(jthread);
2812   java_lang_Thread::set_priority(java_thread, (ThreadPriority)prio);
2813   JavaThread* thr = java_lang_Thread::thread(java_thread);
2814   if (thr != NULL) {                  // Thread not yet started; priority pushed down when it is
2815     Thread::set_priority(thr, (ThreadPriority)prio);
2816   }
2817 JVM_END
2818 
2819 
2820 JVM_ENTRY(void, JVM_Yield(JNIEnv *env, jclass threadClass))
2821   JVMWrapper("JVM_Yield");
2822   if (os::dont_yield()) return;
2823 #ifndef USDT2
2824   HS_DTRACE_PROBE0(hotspot, thread__yield);
2825 #else /* USDT2 */
2826   HOTSPOT_THREAD_YIELD();
2827 #endif /* USDT2 */
2828   // When ConvertYieldToSleep is off (default), this matches the classic VM use of yield.
2829   // Critical for similar threading behaviour
2830   if (ConvertYieldToSleep) {
2831     os::sleep(thread, MinSleepInterval, false);
2832   } else {
2833     os::yield();
2834   }
2835 JVM_END
2836 
2837 
2838 JVM_ENTRY(void, JVM_Sleep(JNIEnv* env, jclass threadClass, jlong millis))
2839   JVMWrapper("JVM_Sleep");
2840 
2841   if (millis < 0) {
2842     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "timeout value is negative");
2843   }
2844 
2845   if (Thread::is_interrupted (THREAD, true) && !HAS_PENDING_EXCEPTION) {
2846     THROW_MSG(vmSymbols::java_lang_InterruptedException(), "sleep interrupted");
2847   }
2848 
2849   // Save current thread state and restore it at the end of this block.
2850   // And set new thread state to SLEEPING.
2851   JavaThreadSleepState jtss(thread);
2852 
2853 #ifndef USDT2
2854   HS_DTRACE_PROBE1(hotspot, thread__sleep__begin, millis);
2855 #else /* USDT2 */
2856   HOTSPOT_THREAD_SLEEP_BEGIN(
2857                              millis);
2858 #endif /* USDT2 */
2859 
2860   if (millis == 0) {
2861     // When ConvertSleepToYield is on, this matches the classic VM implementation of
2862     // JVM_Sleep. Critical for similar threading behaviour (Win32)
2863     // It appears that in certain GUI contexts, it may be beneficial to do a short sleep
2864     // for SOLARIS
2865     if (ConvertSleepToYield) {
2866       os::yield();
2867     } else {
2868       ThreadState old_state = thread->osthread()->get_state();
2869       thread->osthread()->set_state(SLEEPING);
2870       os::sleep(thread, MinSleepInterval, false);
2871       thread->osthread()->set_state(old_state);
2872     }
2873   } else {
2874     ThreadState old_state = thread->osthread()->get_state();
2875     thread->osthread()->set_state(SLEEPING);
2876     if (os::sleep(thread, millis, true) == OS_INTRPT) {
2877       // An asynchronous exception (e.g., ThreadDeathException) could have been thrown on
2878       // us while we were sleeping. We do not overwrite those.
2879       if (!HAS_PENDING_EXCEPTION) {
2880 #ifndef USDT2
2881         HS_DTRACE_PROBE1(hotspot, thread__sleep__end,1);
2882 #else /* USDT2 */
2883         HOTSPOT_THREAD_SLEEP_END(
2884                                  1);
2885 #endif /* USDT2 */
2886         // TODO-FIXME: THROW_MSG returns which means we will not call set_state()
2887         // to properly restore the thread state.  That's likely wrong.
2888         THROW_MSG(vmSymbols::java_lang_InterruptedException(), "sleep interrupted");
2889       }
2890     }
2891     thread->osthread()->set_state(old_state);
2892   }
2893 #ifndef USDT2
2894   HS_DTRACE_PROBE1(hotspot, thread__sleep__end,0);
2895 #else /* USDT2 */
2896   HOTSPOT_THREAD_SLEEP_END(
2897                            0);
2898 #endif /* USDT2 */
2899 JVM_END
2900 
2901 JVM_ENTRY(jobject, JVM_CurrentThread(JNIEnv* env, jclass threadClass))
2902   JVMWrapper("JVM_CurrentThread");
2903   oop jthread = thread->threadObj();
2904   assert (thread != NULL, "no current thread!");
2905   return JNIHandles::make_local(env, jthread);
2906 JVM_END
2907 
2908 
2909 JVM_ENTRY(jint, JVM_CountStackFrames(JNIEnv* env, jobject jthread))
2910   JVMWrapper("JVM_CountStackFrames");
2911 
2912   // Ensure that the C++ Thread and OSThread structures aren't freed before we operate
2913   oop java_thread = JNIHandles::resolve_non_null(jthread);
2914   bool throw_illegal_thread_state = false;
2915   int count = 0;
2916 
2917   {
2918     MutexLockerEx ml(thread->threadObj() == java_thread ? NULL : Threads_lock);
2919     // We need to re-resolve the java_thread, since a GC might have happened during the
2920     // acquire of the lock
2921     JavaThread* thr = java_lang_Thread::thread(JNIHandles::resolve_non_null(jthread));
2922 
2923     if (thr == NULL) {
2924       // do nothing
2925     } else if(! thr->is_external_suspend() || ! thr->frame_anchor()->walkable()) {
2926       // Check whether this java thread has been suspended already. If not, throws
2927       // IllegalThreadStateException. We defer to throw that exception until
2928       // Threads_lock is released since loading exception class has to leave VM.
2929       // The correct way to test a thread is actually suspended is
2930       // wait_for_ext_suspend_completion(), but we can't call that while holding
2931       // the Threads_lock. The above tests are sufficient for our purposes
2932       // provided the walkability of the stack is stable - which it isn't
2933       // 100% but close enough for most practical purposes.
2934       throw_illegal_thread_state = true;
2935     } else {
2936       // Count all java activation, i.e., number of vframes
2937       for(vframeStream vfst(thr); !vfst.at_end(); vfst.next()) {
2938         // Native frames are not counted
2939         if (!vfst.method()->is_native()) count++;
2940        }
2941     }
2942   }
2943 
2944   if (throw_illegal_thread_state) {
2945     THROW_MSG_0(vmSymbols::java_lang_IllegalThreadStateException(),
2946                 "this thread is not suspended");
2947   }
2948   return count;
2949 JVM_END
2950 
2951 // Consider: A better way to implement JVM_Interrupt() is to acquire
2952 // Threads_lock to resolve the jthread into a Thread pointer, fetch
2953 // Thread->platformevent, Thread->native_thr, Thread->parker, etc.,
2954 // drop Threads_lock, and the perform the unpark() and thr_kill() operations
2955 // outside the critical section.  Threads_lock is hot so we want to minimize
2956 // the hold-time.  A cleaner interface would be to decompose interrupt into
2957 // two steps.  The 1st phase, performed under Threads_lock, would return
2958 // a closure that'd be invoked after Threads_lock was dropped.
2959 // This tactic is safe as PlatformEvent and Parkers are type-stable (TSM) and
2960 // admit spurious wakeups.
2961 
2962 JVM_ENTRY(void, JVM_Interrupt(JNIEnv* env, jobject jthread))
2963   JVMWrapper("JVM_Interrupt");
2964 
2965   // Ensure that the C++ Thread and OSThread structures aren't freed before we operate
2966   oop java_thread = JNIHandles::resolve_non_null(jthread);
2967   MutexLockerEx ml(thread->threadObj() == java_thread ? NULL : Threads_lock);
2968   // We need to re-resolve the java_thread, since a GC might have happened during the
2969   // acquire of the lock
2970   JavaThread* thr = java_lang_Thread::thread(JNIHandles::resolve_non_null(jthread));
2971   if (thr != NULL) {
2972     Thread::interrupt(thr);
2973   }
2974 JVM_END
2975 
2976 
2977 JVM_QUICK_ENTRY(jboolean, JVM_IsInterrupted(JNIEnv* env, jobject jthread, jboolean clear_interrupted))
2978   JVMWrapper("JVM_IsInterrupted");
2979 
2980   // Ensure that the C++ Thread and OSThread structures aren't freed before we operate
2981   oop java_thread = JNIHandles::resolve_non_null(jthread);
2982   MutexLockerEx ml(thread->threadObj() == java_thread ? NULL : Threads_lock);
2983   // We need to re-resolve the java_thread, since a GC might have happened during the
2984   // acquire of the lock
2985   JavaThread* thr = java_lang_Thread::thread(JNIHandles::resolve_non_null(jthread));
2986   if (thr == NULL) {
2987     return JNI_FALSE;
2988   } else {
2989     return (jboolean) Thread::is_interrupted(thr, clear_interrupted != 0);
2990   }
2991 JVM_END
2992 
2993 
2994 // Return true iff the current thread has locked the object passed in
2995 
2996 JVM_ENTRY(jboolean, JVM_HoldsLock(JNIEnv* env, jclass threadClass, jobject obj))
2997   JVMWrapper("JVM_HoldsLock");
2998   assert(THREAD->is_Java_thread(), "sanity check");
2999   if (obj == NULL) {
3000     THROW_(vmSymbols::java_lang_NullPointerException(), JNI_FALSE);
3001   }
3002   Handle h_obj(THREAD, JNIHandles::resolve(obj));
3003   return ObjectSynchronizer::current_thread_holds_lock((JavaThread*)THREAD, h_obj);
3004 JVM_END
3005 
3006 
3007 JVM_ENTRY(void, JVM_DumpAllStacks(JNIEnv* env, jclass))
3008   JVMWrapper("JVM_DumpAllStacks");
3009   VM_PrintThreads op;
3010   VMThread::execute(&op);
3011   if (JvmtiExport::should_post_data_dump()) {
3012     JvmtiExport::post_data_dump();
3013   }
3014 JVM_END
3015 
3016 JVM_ENTRY(void, JVM_SetNativeThreadName(JNIEnv* env, jobject jthread, jstring name))
3017   JVMWrapper("JVM_SetNativeThreadName");
3018   ResourceMark rm(THREAD);
3019   oop java_thread = JNIHandles::resolve_non_null(jthread);
3020   JavaThread* thr = java_lang_Thread::thread(java_thread);
3021   // Thread naming only supported for the current thread, doesn't work for
3022   // target threads.
3023   if (Thread::current() == thr && !thr->has_attached_via_jni()) {
3024     // we don't set the name of an attached thread to avoid stepping
3025     // on other programs
3026     const char *thread_name = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(name));
3027     os::set_native_thread_name(thread_name);
3028   }
3029 JVM_END
3030 
3031 // java.lang.SecurityManager ///////////////////////////////////////////////////////////////////////
3032 
3033 static bool is_trusted_frame(JavaThread* jthread, vframeStream* vfst) {
3034   assert(jthread->is_Java_thread(), "must be a Java thread");
3035   if (jthread->privileged_stack_top() == NULL) return false;
3036   if (jthread->privileged_stack_top()->frame_id() == vfst->frame_id()) {
3037     oop loader = jthread->privileged_stack_top()->class_loader();
3038     if (loader == NULL) return true;
3039     bool trusted = java_lang_ClassLoader::is_trusted_loader(loader);
3040     if (trusted) return true;
3041   }
3042   return false;
3043 }
3044 
3045 JVM_ENTRY(jclass, JVM_CurrentLoadedClass(JNIEnv *env))
3046   JVMWrapper("JVM_CurrentLoadedClass");
3047   ResourceMark rm(THREAD);
3048 
3049   for (vframeStream vfst(thread); !vfst.at_end(); vfst.next()) {
3050     // if a method in a class in a trusted loader is in a doPrivileged, return NULL
3051     bool trusted = is_trusted_frame(thread, &vfst);
3052     if (trusted) return NULL;
3053 
3054     methodOop m = vfst.method();
3055     if (!m->is_native()) {
3056       klassOop holder = m->method_holder();
3057       oop      loader = instanceKlass::cast(holder)->class_loader();
3058       if (loader != NULL && !java_lang_ClassLoader::is_trusted_loader(loader)) {
3059         return (jclass) JNIHandles::make_local(env, Klass::cast(holder)->java_mirror());
3060       }
3061     }
3062   }
3063   return NULL;
3064 JVM_END
3065 
3066 
3067 JVM_ENTRY(jobject, JVM_CurrentClassLoader(JNIEnv *env))
3068   JVMWrapper("JVM_CurrentClassLoader");
3069   ResourceMark rm(THREAD);
3070 
3071   for (vframeStream vfst(thread); !vfst.at_end(); vfst.next()) {
3072 
3073     // if a method in a class in a trusted loader is in a doPrivileged, return NULL
3074     bool trusted = is_trusted_frame(thread, &vfst);
3075     if (trusted) return NULL;
3076 
3077     methodOop m = vfst.method();
3078     if (!m->is_native()) {
3079       klassOop holder = m->method_holder();
3080       assert(holder->is_klass(), "just checking");
3081       oop loader = instanceKlass::cast(holder)->class_loader();
3082       if (loader != NULL && !java_lang_ClassLoader::is_trusted_loader(loader)) {
3083         return JNIHandles::make_local(env, loader);
3084       }
3085     }
3086   }
3087   return NULL;
3088 JVM_END
3089 
3090 
3091 // Utility object for collecting method holders walking down the stack
3092 class KlassLink: public ResourceObj {
3093  public:
3094   KlassHandle klass;
3095   KlassLink*  next;
3096 
3097   KlassLink(KlassHandle k) { klass = k; next = NULL; }
3098 };
3099 
3100 
3101 JVM_ENTRY(jobjectArray, JVM_GetClassContext(JNIEnv *env))
3102   JVMWrapper("JVM_GetClassContext");
3103   ResourceMark rm(THREAD);
3104   JvmtiVMObjectAllocEventCollector oam;
3105   // Collect linked list of (handles to) method holders
3106   KlassLink* first = NULL;
3107   KlassLink* last  = NULL;
3108   int depth = 0;
3109 
3110   for(vframeStream vfst(thread); !vfst.at_end(); vfst.security_get_caller_frame(1)) {
3111     // Native frames are not returned
3112     if (!vfst.method()->is_native()) {
3113       klassOop holder = vfst.method()->method_holder();
3114       assert(holder->is_klass(), "just checking");
3115       depth++;
3116       KlassLink* l = new KlassLink(KlassHandle(thread, holder));
3117       if (first == NULL) {
3118         first = last = l;
3119       } else {
3120         last->next = l;
3121         last = l;
3122       }
3123     }
3124   }
3125 
3126   // Create result array of type [Ljava/lang/Class;
3127   objArrayOop result = oopFactory::new_objArray(SystemDictionary::Class_klass(), depth, CHECK_NULL);
3128   // Fill in mirrors corresponding to method holders
3129   int index = 0;
3130   while (first != NULL) {
3131     result->obj_at_put(index++, Klass::cast(first->klass())->java_mirror());
3132     first = first->next;
3133   }
3134   assert(index == depth, "just checking");
3135 
3136   return (jobjectArray) JNIHandles::make_local(env, result);
3137 JVM_END
3138 
3139 
3140 JVM_ENTRY(jint, JVM_ClassDepth(JNIEnv *env, jstring name))
3141   JVMWrapper("JVM_ClassDepth");
3142   ResourceMark rm(THREAD);
3143   Handle h_name (THREAD, JNIHandles::resolve_non_null(name));
3144   Handle class_name_str = java_lang_String::internalize_classname(h_name, CHECK_0);
3145 
3146   const char* str = java_lang_String::as_utf8_string(class_name_str());
3147   TempNewSymbol class_name_sym = SymbolTable::probe(str, (int)strlen(str));
3148   if (class_name_sym == NULL) {
3149     return -1;
3150   }
3151 
3152   int depth = 0;
3153 
3154   for(vframeStream vfst(thread); !vfst.at_end(); vfst.next()) {
3155     if (!vfst.method()->is_native()) {
3156       klassOop holder = vfst.method()->method_holder();
3157       assert(holder->is_klass(), "just checking");
3158       if (instanceKlass::cast(holder)->name() == class_name_sym) {
3159         return depth;
3160       }
3161       depth++;
3162     }
3163   }
3164   return -1;
3165 JVM_END
3166 
3167 
3168 JVM_ENTRY(jint, JVM_ClassLoaderDepth(JNIEnv *env))
3169   JVMWrapper("JVM_ClassLoaderDepth");
3170   ResourceMark rm(THREAD);
3171   int depth = 0;
3172   for (vframeStream vfst(thread); !vfst.at_end(); vfst.next()) {
3173     // if a method in a class in a trusted loader is in a doPrivileged, return -1
3174     bool trusted = is_trusted_frame(thread, &vfst);
3175     if (trusted) return -1;
3176 
3177     methodOop m = vfst.method();
3178     if (!m->is_native()) {
3179       klassOop holder = m->method_holder();
3180       assert(holder->is_klass(), "just checking");
3181       oop loader = instanceKlass::cast(holder)->class_loader();
3182       if (loader != NULL && !java_lang_ClassLoader::is_trusted_loader(loader)) {
3183         return depth;
3184       }
3185       depth++;
3186     }
3187   }
3188   return -1;
3189 JVM_END
3190 
3191 
3192 // java.lang.Package ////////////////////////////////////////////////////////////////
3193 
3194 
3195 JVM_ENTRY(jstring, JVM_GetSystemPackage(JNIEnv *env, jstring name))
3196   JVMWrapper("JVM_GetSystemPackage");
3197   ResourceMark rm(THREAD);
3198   JvmtiVMObjectAllocEventCollector oam;
3199   char* str = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(name));
3200   oop result = ClassLoader::get_system_package(str, CHECK_NULL);
3201   return (jstring) JNIHandles::make_local(result);
3202 JVM_END
3203 
3204 
3205 JVM_ENTRY(jobjectArray, JVM_GetSystemPackages(JNIEnv *env))
3206   JVMWrapper("JVM_GetSystemPackages");
3207   JvmtiVMObjectAllocEventCollector oam;
3208   objArrayOop result = ClassLoader::get_system_packages(CHECK_NULL);
3209   return (jobjectArray) JNIHandles::make_local(result);
3210 JVM_END
3211 
3212 
3213 // ObjectInputStream ///////////////////////////////////////////////////////////////
3214 
3215 bool force_verify_field_access(klassOop current_class, klassOop field_class, AccessFlags access, bool classloader_only) {
3216   if (current_class == NULL) {
3217     return true;
3218   }
3219   if ((current_class == field_class) || access.is_public()) {
3220     return true;
3221   }
3222 
3223   if (access.is_protected()) {
3224     // See if current_class is a subclass of field_class
3225     if (Klass::cast(current_class)->is_subclass_of(field_class)) {
3226       return true;
3227     }
3228   }
3229 
3230   return (!access.is_private() && instanceKlass::cast(current_class)->is_same_class_package(field_class));
3231 }
3232 
3233 
3234 // JVM_AllocateNewObject and JVM_AllocateNewArray are unused as of 1.4
3235 JVM_ENTRY(jobject, JVM_AllocateNewObject(JNIEnv *env, jobject receiver, jclass currClass, jclass initClass))
3236   JVMWrapper("JVM_AllocateNewObject");
3237   JvmtiVMObjectAllocEventCollector oam;
3238   // Receiver is not used
3239   oop curr_mirror = JNIHandles::resolve_non_null(currClass);
3240   oop init_mirror = JNIHandles::resolve_non_null(initClass);
3241 
3242   // Cannot instantiate primitive types
3243   if (java_lang_Class::is_primitive(curr_mirror) || java_lang_Class::is_primitive(init_mirror)) {
3244     ResourceMark rm(THREAD);
3245     THROW_0(vmSymbols::java_lang_InvalidClassException());
3246   }
3247 
3248   // Arrays not allowed here, must use JVM_AllocateNewArray
3249   if (Klass::cast(java_lang_Class::as_klassOop(curr_mirror))->oop_is_javaArray() ||
3250       Klass::cast(java_lang_Class::as_klassOop(init_mirror))->oop_is_javaArray()) {
3251     ResourceMark rm(THREAD);
3252     THROW_0(vmSymbols::java_lang_InvalidClassException());
3253   }
3254 
3255   instanceKlassHandle curr_klass (THREAD, java_lang_Class::as_klassOop(curr_mirror));
3256   instanceKlassHandle init_klass (THREAD, java_lang_Class::as_klassOop(init_mirror));
3257 
3258   assert(curr_klass->is_subclass_of(init_klass()), "just checking");
3259 
3260   // Interfaces, abstract classes, and java.lang.Class classes cannot be instantiated directly.
3261   curr_klass->check_valid_for_instantiation(false, CHECK_NULL);
3262 
3263   // Make sure klass is initialized, since we are about to instantiate one of them.
3264   curr_klass->initialize(CHECK_NULL);
3265 
3266  methodHandle m (THREAD,
3267                  init_klass->find_method(vmSymbols::object_initializer_name(),
3268                                          vmSymbols::void_method_signature()));
3269   if (m.is_null()) {
3270     ResourceMark rm(THREAD);
3271     THROW_MSG_0(vmSymbols::java_lang_NoSuchMethodError(),
3272                 methodOopDesc::name_and_sig_as_C_string(Klass::cast(init_klass()),
3273                                           vmSymbols::object_initializer_name(),
3274                                           vmSymbols::void_method_signature()));
3275   }
3276 
3277   if (curr_klass ==  init_klass && !m->is_public()) {
3278     // Calling the constructor for class 'curr_klass'.
3279     // Only allow calls to a public no-arg constructor.
3280     // This path corresponds to creating an Externalizable object.
3281     THROW_0(vmSymbols::java_lang_IllegalAccessException());
3282   }
3283 
3284   if (!force_verify_field_access(curr_klass(), init_klass(), m->access_flags(), false)) {
3285     // subclass 'curr_klass' does not have access to no-arg constructor of 'initcb'
3286     THROW_0(vmSymbols::java_lang_IllegalAccessException());
3287   }
3288 
3289   Handle obj = curr_klass->allocate_instance_handle(CHECK_NULL);
3290   // Call constructor m. This might call a constructor higher up in the hierachy
3291   JavaCalls::call_default_constructor(thread, m, obj, CHECK_NULL);
3292 
3293   return JNIHandles::make_local(obj());
3294 JVM_END
3295 
3296 
3297 JVM_ENTRY(jobject, JVM_AllocateNewArray(JNIEnv *env, jobject obj, jclass currClass, jint length))
3298   JVMWrapper("JVM_AllocateNewArray");
3299   JvmtiVMObjectAllocEventCollector oam;
3300   oop mirror = JNIHandles::resolve_non_null(currClass);
3301 
3302   if (java_lang_Class::is_primitive(mirror)) {
3303     THROW_0(vmSymbols::java_lang_InvalidClassException());
3304   }
3305   klassOop k = java_lang_Class::as_klassOop(mirror);
3306   oop result;
3307 
3308   if (k->klass_part()->oop_is_typeArray()) {
3309     // typeArray
3310     result = typeArrayKlass::cast(k)->allocate(length, CHECK_NULL);
3311   } else if (k->klass_part()->oop_is_objArray()) {
3312     // objArray
3313     objArrayKlassHandle oak(THREAD, k);
3314     oak->initialize(CHECK_NULL); // make sure class is initialized (matches Classic VM behavior)
3315     result = oak->allocate(length, CHECK_NULL);
3316   } else {
3317     THROW_0(vmSymbols::java_lang_InvalidClassException());
3318   }
3319   return JNIHandles::make_local(env, result);
3320 JVM_END
3321 
3322 
3323 // Return the first non-null class loader up the execution stack, or null
3324 // if only code from the null class loader is on the stack.
3325 
3326 JVM_ENTRY(jobject, JVM_LatestUserDefinedLoader(JNIEnv *env))
3327   for (vframeStream vfst(thread); !vfst.at_end(); vfst.next()) {
3328     // UseNewReflection
3329     vfst.skip_reflection_related_frames(); // Only needed for 1.4 reflection
3330     klassOop holder = vfst.method()->method_holder();
3331     oop loader = instanceKlass::cast(holder)->class_loader();
3332     if (loader != NULL) {
3333       return JNIHandles::make_local(env, loader);
3334     }
3335   }
3336   return NULL;
3337 JVM_END
3338 
3339 
3340 // Load a class relative to the most recent class on the stack  with a non-null
3341 // classloader.
3342 // This function has been deprecated and should not be considered part of the
3343 // specified JVM interface.
3344 
3345 JVM_ENTRY(jclass, JVM_LoadClass0(JNIEnv *env, jobject receiver,
3346                                  jclass currClass, jstring currClassName))
3347   JVMWrapper("JVM_LoadClass0");
3348   // Receiver is not used
3349   ResourceMark rm(THREAD);
3350 
3351   // Class name argument is not guaranteed to be in internal format
3352   Handle classname (THREAD, JNIHandles::resolve_non_null(currClassName));
3353   Handle string = java_lang_String::internalize_classname(classname, CHECK_NULL);
3354 
3355   const char* str = java_lang_String::as_utf8_string(string());
3356 
3357   if (str == NULL || (int)strlen(str) > Symbol::max_length()) {
3358     // It's impossible to create this class;  the name cannot fit
3359     // into the constant pool.
3360     THROW_MSG_0(vmSymbols::java_lang_NoClassDefFoundError(), str);
3361   }
3362 
3363   TempNewSymbol name = SymbolTable::new_symbol(str, CHECK_NULL);
3364   Handle curr_klass (THREAD, JNIHandles::resolve(currClass));
3365   // Find the most recent class on the stack with a non-null classloader
3366   oop loader = NULL;
3367   oop protection_domain = NULL;
3368   if (curr_klass.is_null()) {
3369     for (vframeStream vfst(thread);
3370          !vfst.at_end() && loader == NULL;
3371          vfst.next()) {
3372       if (!vfst.method()->is_native()) {
3373         klassOop holder = vfst.method()->method_holder();
3374         loader             = instanceKlass::cast(holder)->class_loader();
3375         protection_domain  = instanceKlass::cast(holder)->protection_domain();
3376       }
3377     }
3378   } else {
3379     klassOop curr_klass_oop = java_lang_Class::as_klassOop(curr_klass());
3380     loader            = instanceKlass::cast(curr_klass_oop)->class_loader();
3381     protection_domain = instanceKlass::cast(curr_klass_oop)->protection_domain();
3382   }
3383   Handle h_loader(THREAD, loader);
3384   Handle h_prot  (THREAD, protection_domain);
3385   jclass result =  find_class_from_class_loader(env, name, true, h_loader, h_prot,
3386                                                 false, thread);
3387   if (TraceClassResolution && result != NULL) {
3388     trace_class_resolution(java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(result)));
3389   }
3390   return result;
3391 JVM_END
3392 
3393 
3394 // Array ///////////////////////////////////////////////////////////////////////////////////////////
3395 
3396 
3397 // resolve array handle and check arguments
3398 static inline arrayOop check_array(JNIEnv *env, jobject arr, bool type_array_only, TRAPS) {
3399   if (arr == NULL) {
3400     THROW_0(vmSymbols::java_lang_NullPointerException());
3401   }
3402   oop a = JNIHandles::resolve_non_null(arr);
3403   if (!a->is_javaArray() || (type_array_only && !a->is_typeArray())) {
3404     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Argument is not an array");
3405   }
3406   return arrayOop(a);
3407 }
3408 
3409 
3410 JVM_ENTRY(jint, JVM_GetArrayLength(JNIEnv *env, jobject arr))
3411   JVMWrapper("JVM_GetArrayLength");
3412   arrayOop a = check_array(env, arr, false, CHECK_0);
3413   return a->length();
3414 JVM_END
3415 
3416 
3417 JVM_ENTRY(jobject, JVM_GetArrayElement(JNIEnv *env, jobject arr, jint index))
3418   JVMWrapper("JVM_Array_Get");
3419   JvmtiVMObjectAllocEventCollector oam;
3420   arrayOop a = check_array(env, arr, false, CHECK_NULL);
3421   jvalue value;
3422   BasicType type = Reflection::array_get(&value, a, index, CHECK_NULL);
3423   oop box = Reflection::box(&value, type, CHECK_NULL);
3424   return JNIHandles::make_local(env, box);
3425 JVM_END
3426 
3427 
3428 JVM_ENTRY(jvalue, JVM_GetPrimitiveArrayElement(JNIEnv *env, jobject arr, jint index, jint wCode))
3429   JVMWrapper("JVM_GetPrimitiveArrayElement");
3430   jvalue value;
3431   value.i = 0; // to initialize value before getting used in CHECK
3432   arrayOop a = check_array(env, arr, true, CHECK_(value));
3433   assert(a->is_typeArray(), "just checking");
3434   BasicType type = Reflection::array_get(&value, a, index, CHECK_(value));
3435   BasicType wide_type = (BasicType) wCode;
3436   if (type != wide_type) {
3437     Reflection::widen(&value, type, wide_type, CHECK_(value));
3438   }
3439   return value;
3440 JVM_END
3441 
3442 
3443 JVM_ENTRY(void, JVM_SetArrayElement(JNIEnv *env, jobject arr, jint index, jobject val))
3444   JVMWrapper("JVM_SetArrayElement");
3445   arrayOop a = check_array(env, arr, false, CHECK);
3446   oop box = JNIHandles::resolve(val);
3447   jvalue value;
3448   value.i = 0; // to initialize value before getting used in CHECK
3449   BasicType value_type;
3450   if (a->is_objArray()) {
3451     // Make sure we do no unbox e.g. java/lang/Integer instances when storing into an object array
3452     value_type = Reflection::unbox_for_regular_object(box, &value);
3453   } else {
3454     value_type = Reflection::unbox_for_primitive(box, &value, CHECK);
3455   }
3456   Reflection::array_set(&value, a, index, value_type, CHECK);
3457 JVM_END
3458 
3459 
3460 JVM_ENTRY(void, JVM_SetPrimitiveArrayElement(JNIEnv *env, jobject arr, jint index, jvalue v, unsigned char vCode))
3461   JVMWrapper("JVM_SetPrimitiveArrayElement");
3462   arrayOop a = check_array(env, arr, true, CHECK);
3463   assert(a->is_typeArray(), "just checking");
3464   BasicType value_type = (BasicType) vCode;
3465   Reflection::array_set(&v, a, index, value_type, CHECK);
3466 JVM_END
3467 
3468 
3469 JVM_ENTRY(jobject, JVM_NewArray(JNIEnv *env, jclass eltClass, jint length))
3470   JVMWrapper("JVM_NewArray");
3471   JvmtiVMObjectAllocEventCollector oam;
3472   oop element_mirror = JNIHandles::resolve(eltClass);
3473   oop result = Reflection::reflect_new_array(element_mirror, length, CHECK_NULL);
3474   return JNIHandles::make_local(env, result);
3475 JVM_END
3476 
3477 
3478 JVM_ENTRY(jobject, JVM_NewMultiArray(JNIEnv *env, jclass eltClass, jintArray dim))
3479   JVMWrapper("JVM_NewMultiArray");
3480   JvmtiVMObjectAllocEventCollector oam;
3481   arrayOop dim_array = check_array(env, dim, true, CHECK_NULL);
3482   oop element_mirror = JNIHandles::resolve(eltClass);
3483   assert(dim_array->is_typeArray(), "just checking");
3484   oop result = Reflection::reflect_new_multi_array(element_mirror, typeArrayOop(dim_array), CHECK_NULL);
3485   return JNIHandles::make_local(env, result);
3486 JVM_END
3487 
3488 
3489 // Networking library support ////////////////////////////////////////////////////////////////////
3490 
3491 JVM_LEAF(jint, JVM_InitializeSocketLibrary())
3492   JVMWrapper("JVM_InitializeSocketLibrary");
3493   return 0;
3494 JVM_END
3495 
3496 
3497 JVM_LEAF(jint, JVM_Socket(jint domain, jint type, jint protocol))
3498   JVMWrapper("JVM_Socket");
3499   return os::socket(domain, type, protocol);
3500 JVM_END
3501 
3502 
3503 JVM_LEAF(jint, JVM_SocketClose(jint fd))
3504   JVMWrapper2("JVM_SocketClose (0x%x)", fd);
3505   //%note jvm_r6
3506   return os::socket_close(fd);
3507 JVM_END
3508 
3509 
3510 JVM_LEAF(jint, JVM_SocketShutdown(jint fd, jint howto))
3511   JVMWrapper2("JVM_SocketShutdown (0x%x)", fd);
3512   //%note jvm_r6
3513   return os::socket_shutdown(fd, howto);
3514 JVM_END
3515 
3516 
3517 JVM_LEAF(jint, JVM_Recv(jint fd, char *buf, jint nBytes, jint flags))
3518   JVMWrapper2("JVM_Recv (0x%x)", fd);
3519   //%note jvm_r6
3520   return os::recv(fd, buf, (size_t)nBytes, (uint)flags);
3521 JVM_END
3522 
3523 
3524 JVM_LEAF(jint, JVM_Send(jint fd, char *buf, jint nBytes, jint flags))
3525   JVMWrapper2("JVM_Send (0x%x)", fd);
3526   //%note jvm_r6
3527   return os::send(fd, buf, (size_t)nBytes, (uint)flags);
3528 JVM_END
3529 
3530 
3531 JVM_LEAF(jint, JVM_Timeout(int fd, long timeout))
3532   JVMWrapper2("JVM_Timeout (0x%x)", fd);
3533   //%note jvm_r6
3534   return os::timeout(fd, timeout);
3535 JVM_END
3536 
3537 
3538 JVM_LEAF(jint, JVM_Listen(jint fd, jint count))
3539   JVMWrapper2("JVM_Listen (0x%x)", fd);
3540   //%note jvm_r6
3541   return os::listen(fd, count);
3542 JVM_END
3543 
3544 
3545 JVM_LEAF(jint, JVM_Connect(jint fd, struct sockaddr *him, jint len))
3546   JVMWrapper2("JVM_Connect (0x%x)", fd);
3547   //%note jvm_r6
3548   return os::connect(fd, him, (socklen_t)len);
3549 JVM_END
3550 
3551 
3552 JVM_LEAF(jint, JVM_Bind(jint fd, struct sockaddr *him, jint len))
3553   JVMWrapper2("JVM_Bind (0x%x)", fd);
3554   //%note jvm_r6
3555   return os::bind(fd, him, (socklen_t)len);
3556 JVM_END
3557 
3558 
3559 JVM_LEAF(jint, JVM_Accept(jint fd, struct sockaddr *him, jint *len))
3560   JVMWrapper2("JVM_Accept (0x%x)", fd);
3561   //%note jvm_r6
3562   socklen_t socklen = (socklen_t)(*len);
3563   jint result = os::accept(fd, him, &socklen);
3564   *len = (jint)socklen;
3565   return result;
3566 JVM_END
3567 
3568 
3569 JVM_LEAF(jint, JVM_RecvFrom(jint fd, char *buf, int nBytes, int flags, struct sockaddr *from, int *fromlen))
3570   JVMWrapper2("JVM_RecvFrom (0x%x)", fd);
3571   //%note jvm_r6
3572   socklen_t socklen = (socklen_t)(*fromlen);
3573   jint result = os::recvfrom(fd, buf, (size_t)nBytes, (uint)flags, from, &socklen);
3574   *fromlen = (int)socklen;
3575   return result;
3576 JVM_END
3577 
3578 
3579 JVM_LEAF(jint, JVM_GetSockName(jint fd, struct sockaddr *him, int *len))
3580   JVMWrapper2("JVM_GetSockName (0x%x)", fd);
3581   //%note jvm_r6
3582   socklen_t socklen = (socklen_t)(*len);
3583   jint result = os::get_sock_name(fd, him, &socklen);
3584   *len = (int)socklen;
3585   return result;
3586 JVM_END
3587 
3588 
3589 JVM_LEAF(jint, JVM_SendTo(jint fd, char *buf, int len, int flags, struct sockaddr *to, int tolen))
3590   JVMWrapper2("JVM_SendTo (0x%x)", fd);
3591   //%note jvm_r6
3592   return os::sendto(fd, buf, (size_t)len, (uint)flags, to, (socklen_t)tolen);
3593 JVM_END
3594 
3595 
3596 JVM_LEAF(jint, JVM_SocketAvailable(jint fd, jint *pbytes))
3597   JVMWrapper2("JVM_SocketAvailable (0x%x)", fd);
3598   //%note jvm_r6
3599   return os::socket_available(fd, pbytes);
3600 JVM_END
3601 
3602 
3603 JVM_LEAF(jint, JVM_GetSockOpt(jint fd, int level, int optname, char *optval, int *optlen))
3604   JVMWrapper2("JVM_GetSockOpt (0x%x)", fd);
3605   //%note jvm_r6
3606   socklen_t socklen = (socklen_t)(*optlen);
3607   jint result = os::get_sock_opt(fd, level, optname, optval, &socklen);
3608   *optlen = (int)socklen;
3609   return result;
3610 JVM_END
3611 
3612 
3613 JVM_LEAF(jint, JVM_SetSockOpt(jint fd, int level, int optname, const char *optval, int optlen))
3614   JVMWrapper2("JVM_GetSockOpt (0x%x)", fd);
3615   //%note jvm_r6
3616   return os::set_sock_opt(fd, level, optname, optval, (socklen_t)optlen);
3617 JVM_END
3618 
3619 
3620 JVM_LEAF(int, JVM_GetHostName(char* name, int namelen))
3621   JVMWrapper("JVM_GetHostName");
3622   return os::get_host_name(name, namelen);
3623 JVM_END
3624 
3625 
3626 // Library support ///////////////////////////////////////////////////////////////////////////
3627 
3628 JVM_ENTRY_NO_ENV(void*, JVM_LoadLibrary(const char* name))
3629   //%note jvm_ct
3630   JVMWrapper2("JVM_LoadLibrary (%s)", name);
3631   char ebuf[1024];
3632   void *load_result;
3633   {
3634     ThreadToNativeFromVM ttnfvm(thread);
3635     load_result = os::dll_load(name, ebuf, sizeof ebuf);
3636   }
3637   if (load_result == NULL) {
3638     char msg[1024];
3639     jio_snprintf(msg, sizeof msg, "%s: %s", name, ebuf);
3640     // Since 'ebuf' may contain a string encoded using
3641     // platform encoding scheme, we need to pass
3642     // Exceptions::unsafe_to_utf8 to the new_exception method
3643     // as the last argument. See bug 6367357.
3644     Handle h_exception =
3645       Exceptions::new_exception(thread,
3646                                 vmSymbols::java_lang_UnsatisfiedLinkError(),
3647                                 msg, Exceptions::unsafe_to_utf8);
3648 
3649     THROW_HANDLE_0(h_exception);
3650   }
3651   return load_result;
3652 JVM_END
3653 
3654 
3655 JVM_LEAF(void, JVM_UnloadLibrary(void* handle))
3656   JVMWrapper("JVM_UnloadLibrary");
3657   os::dll_unload(handle);
3658 JVM_END
3659 
3660 
3661 JVM_LEAF(void*, JVM_FindLibraryEntry(void* handle, const char* name))
3662   JVMWrapper2("JVM_FindLibraryEntry (%s)", name);
3663   return os::dll_lookup(handle, name);
3664 JVM_END
3665 
3666 
3667 // Floating point support ////////////////////////////////////////////////////////////////////
3668 
3669 JVM_LEAF(jboolean, JVM_IsNaN(jdouble a))
3670   JVMWrapper("JVM_IsNaN");
3671   return g_isnan(a);
3672 JVM_END
3673 
3674 
3675 // JNI version ///////////////////////////////////////////////////////////////////////////////
3676 
3677 JVM_LEAF(jboolean, JVM_IsSupportedJNIVersion(jint version))
3678   JVMWrapper2("JVM_IsSupportedJNIVersion (%d)", version);
3679   return Threads::is_supported_jni_version_including_1_1(version);
3680 JVM_END
3681 
3682 
3683 // String support ///////////////////////////////////////////////////////////////////////////
3684 
3685 JVM_ENTRY(jstring, JVM_InternString(JNIEnv *env, jstring str))
3686   JVMWrapper("JVM_InternString");
3687   JvmtiVMObjectAllocEventCollector oam;
3688   if (str == NULL) return NULL;
3689   oop string = JNIHandles::resolve_non_null(str);
3690   oop result = StringTable::intern(string, CHECK_NULL);
3691   return (jstring) JNIHandles::make_local(env, result);
3692 JVM_END
3693 
3694 
3695 // Raw monitor support //////////////////////////////////////////////////////////////////////
3696 
3697 // The lock routine below calls lock_without_safepoint_check in order to get a raw lock
3698 // without interfering with the safepoint mechanism. The routines are not JVM_LEAF because
3699 // they might be called by non-java threads. The JVM_LEAF installs a NoHandleMark check
3700 // that only works with java threads.
3701 
3702 
3703 JNIEXPORT void* JNICALL JVM_RawMonitorCreate(void) {
3704   VM_Exit::block_if_vm_exited();
3705   JVMWrapper("JVM_RawMonitorCreate");
3706   return new Mutex(Mutex::native, "JVM_RawMonitorCreate");
3707 }
3708 
3709 
3710 JNIEXPORT void JNICALL  JVM_RawMonitorDestroy(void *mon) {
3711   VM_Exit::block_if_vm_exited();
3712   JVMWrapper("JVM_RawMonitorDestroy");
3713   delete ((Mutex*) mon);
3714 }
3715 
3716 
3717 JNIEXPORT jint JNICALL JVM_RawMonitorEnter(void *mon) {
3718   VM_Exit::block_if_vm_exited();
3719   JVMWrapper("JVM_RawMonitorEnter");
3720   ((Mutex*) mon)->jvm_raw_lock();
3721   return 0;
3722 }
3723 
3724 
3725 JNIEXPORT void JNICALL JVM_RawMonitorExit(void *mon) {
3726   VM_Exit::block_if_vm_exited();
3727   JVMWrapper("JVM_RawMonitorExit");
3728   ((Mutex*) mon)->jvm_raw_unlock();
3729 }
3730 
3731 
3732 // Support for Serialization
3733 
3734 typedef jfloat  (JNICALL *IntBitsToFloatFn  )(JNIEnv* env, jclass cb, jint    value);
3735 typedef jdouble (JNICALL *LongBitsToDoubleFn)(JNIEnv* env, jclass cb, jlong   value);
3736 typedef jint    (JNICALL *FloatToIntBitsFn  )(JNIEnv* env, jclass cb, jfloat  value);
3737 typedef jlong   (JNICALL *DoubleToLongBitsFn)(JNIEnv* env, jclass cb, jdouble value);
3738 
3739 static IntBitsToFloatFn   int_bits_to_float_fn   = NULL;
3740 static LongBitsToDoubleFn long_bits_to_double_fn = NULL;
3741 static FloatToIntBitsFn   float_to_int_bits_fn   = NULL;
3742 static DoubleToLongBitsFn double_to_long_bits_fn = NULL;
3743 
3744 
3745 void initialize_converter_functions() {
3746   if (JDK_Version::is_gte_jdk14x_version()) {
3747     // These functions only exist for compatibility with 1.3.1 and earlier
3748     return;
3749   }
3750 
3751   // called from universe_post_init()
3752   assert(
3753     int_bits_to_float_fn   == NULL &&
3754     long_bits_to_double_fn == NULL &&
3755     float_to_int_bits_fn   == NULL &&
3756     double_to_long_bits_fn == NULL ,
3757     "initialization done twice"
3758   );
3759   // initialize
3760   int_bits_to_float_fn   = CAST_TO_FN_PTR(IntBitsToFloatFn  , NativeLookup::base_library_lookup("java/lang/Float" , "intBitsToFloat"  , "(I)F"));
3761   long_bits_to_double_fn = CAST_TO_FN_PTR(LongBitsToDoubleFn, NativeLookup::base_library_lookup("java/lang/Double", "longBitsToDouble", "(J)D"));
3762   float_to_int_bits_fn   = CAST_TO_FN_PTR(FloatToIntBitsFn  , NativeLookup::base_library_lookup("java/lang/Float" , "floatToIntBits"  , "(F)I"));
3763   double_to_long_bits_fn = CAST_TO_FN_PTR(DoubleToLongBitsFn, NativeLookup::base_library_lookup("java/lang/Double", "doubleToLongBits", "(D)J"));
3764   // verify
3765   assert(
3766     int_bits_to_float_fn   != NULL &&
3767     long_bits_to_double_fn != NULL &&
3768     float_to_int_bits_fn   != NULL &&
3769     double_to_long_bits_fn != NULL ,
3770     "initialization failed"
3771   );
3772 }
3773 
3774 
3775 // Serialization
3776 JVM_ENTRY(void, JVM_SetPrimitiveFieldValues(JNIEnv *env, jclass cb, jobject obj,
3777                                             jlongArray fieldIDs, jcharArray typecodes, jbyteArray data))
3778   assert(!JDK_Version::is_gte_jdk14x_version(), "should only be used in 1.3.1 and earlier");
3779 
3780   typeArrayOop tcodes = typeArrayOop(JNIHandles::resolve(typecodes));
3781   typeArrayOop dbuf   = typeArrayOop(JNIHandles::resolve(data));
3782   typeArrayOop fids   = typeArrayOop(JNIHandles::resolve(fieldIDs));
3783   oop          o      = JNIHandles::resolve(obj);
3784 
3785   if (o == NULL || fids == NULL  || dbuf == NULL  || tcodes == NULL) {
3786     THROW(vmSymbols::java_lang_NullPointerException());
3787   }
3788 
3789   jsize nfids = fids->length();
3790   if (nfids == 0) return;
3791 
3792   if (tcodes->length() < nfids) {
3793     THROW(vmSymbols::java_lang_ArrayIndexOutOfBoundsException());
3794   }
3795 
3796   jsize off = 0;
3797   /* loop through fields, setting values */
3798   for (jsize i = 0; i < nfids; i++) {
3799     jfieldID fid = (jfieldID)(intptr_t) fids->long_at(i);
3800     int field_offset;
3801     if (fid != NULL) {
3802       // NULL is a legal value for fid, but retrieving the field offset
3803       // trigger assertion in that case
3804       field_offset = jfieldIDWorkaround::from_instance_jfieldID(o->klass(), fid);
3805     }
3806 
3807     switch (tcodes->char_at(i)) {
3808       case 'Z':
3809         if (fid != NULL) {
3810           jboolean val = (dbuf->byte_at(off) != 0) ? JNI_TRUE : JNI_FALSE;
3811           o->bool_field_put(field_offset, val);
3812         }
3813         off++;
3814         break;
3815 
3816       case 'B':
3817         if (fid != NULL) {
3818           o->byte_field_put(field_offset, dbuf->byte_at(off));
3819         }
3820         off++;
3821         break;
3822 
3823       case 'C':
3824         if (fid != NULL) {
3825           jchar val = ((dbuf->byte_at(off + 0) & 0xFF) << 8)
3826                     + ((dbuf->byte_at(off + 1) & 0xFF) << 0);
3827           o->char_field_put(field_offset, val);
3828         }
3829         off += 2;
3830         break;
3831 
3832       case 'S':
3833         if (fid != NULL) {
3834           jshort val = ((dbuf->byte_at(off + 0) & 0xFF) << 8)
3835                      + ((dbuf->byte_at(off + 1) & 0xFF) << 0);
3836           o->short_field_put(field_offset, val);
3837         }
3838         off += 2;
3839         break;
3840 
3841       case 'I':
3842         if (fid != NULL) {
3843           jint ival = ((dbuf->byte_at(off + 0) & 0xFF) << 24)
3844                     + ((dbuf->byte_at(off + 1) & 0xFF) << 16)
3845                     + ((dbuf->byte_at(off + 2) & 0xFF) << 8)
3846                     + ((dbuf->byte_at(off + 3) & 0xFF) << 0);
3847           o->int_field_put(field_offset, ival);
3848         }
3849         off += 4;
3850         break;
3851 
3852       case 'F':
3853         if (fid != NULL) {
3854           jint ival = ((dbuf->byte_at(off + 0) & 0xFF) << 24)
3855                     + ((dbuf->byte_at(off + 1) & 0xFF) << 16)
3856                     + ((dbuf->byte_at(off + 2) & 0xFF) << 8)
3857                     + ((dbuf->byte_at(off + 3) & 0xFF) << 0);
3858           jfloat fval = (*int_bits_to_float_fn)(env, NULL, ival);
3859           o->float_field_put(field_offset, fval);
3860         }
3861         off += 4;
3862         break;
3863 
3864       case 'J':
3865         if (fid != NULL) {
3866           jlong lval = (((jlong) dbuf->byte_at(off + 0) & 0xFF) << 56)
3867                      + (((jlong) dbuf->byte_at(off + 1) & 0xFF) << 48)
3868                      + (((jlong) dbuf->byte_at(off + 2) & 0xFF) << 40)
3869                      + (((jlong) dbuf->byte_at(off + 3) & 0xFF) << 32)
3870                      + (((jlong) dbuf->byte_at(off + 4) & 0xFF) << 24)
3871                      + (((jlong) dbuf->byte_at(off + 5) & 0xFF) << 16)
3872                      + (((jlong) dbuf->byte_at(off + 6) & 0xFF) << 8)
3873                      + (((jlong) dbuf->byte_at(off + 7) & 0xFF) << 0);
3874           o->long_field_put(field_offset, lval);
3875         }
3876         off += 8;
3877         break;
3878 
3879       case 'D':
3880         if (fid != NULL) {
3881           jlong lval = (((jlong) dbuf->byte_at(off + 0) & 0xFF) << 56)
3882                      + (((jlong) dbuf->byte_at(off + 1) & 0xFF) << 48)
3883                      + (((jlong) dbuf->byte_at(off + 2) & 0xFF) << 40)
3884                      + (((jlong) dbuf->byte_at(off + 3) & 0xFF) << 32)
3885                      + (((jlong) dbuf->byte_at(off + 4) & 0xFF) << 24)
3886                      + (((jlong) dbuf->byte_at(off + 5) & 0xFF) << 16)
3887                      + (((jlong) dbuf->byte_at(off + 6) & 0xFF) << 8)
3888                      + (((jlong) dbuf->byte_at(off + 7) & 0xFF) << 0);
3889           jdouble dval = (*long_bits_to_double_fn)(env, NULL, lval);
3890           o->double_field_put(field_offset, dval);
3891         }
3892         off += 8;
3893         break;
3894 
3895       default:
3896         // Illegal typecode
3897         THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "illegal typecode");
3898     }
3899   }
3900 JVM_END
3901 
3902 
3903 JVM_ENTRY(void, JVM_GetPrimitiveFieldValues(JNIEnv *env, jclass cb, jobject obj,
3904                             jlongArray fieldIDs, jcharArray typecodes, jbyteArray data))
3905   assert(!JDK_Version::is_gte_jdk14x_version(), "should only be used in 1.3.1 and earlier");
3906 
3907   typeArrayOop tcodes = typeArrayOop(JNIHandles::resolve(typecodes));
3908   typeArrayOop dbuf   = typeArrayOop(JNIHandles::resolve(data));
3909   typeArrayOop fids   = typeArrayOop(JNIHandles::resolve(fieldIDs));
3910   oop          o      = JNIHandles::resolve(obj);
3911 
3912   if (o == NULL || fids == NULL  || dbuf == NULL  || tcodes == NULL) {
3913     THROW(vmSymbols::java_lang_NullPointerException());
3914   }
3915 
3916   jsize nfids = fids->length();
3917   if (nfids == 0) return;
3918 
3919   if (tcodes->length() < nfids) {
3920     THROW(vmSymbols::java_lang_ArrayIndexOutOfBoundsException());
3921   }
3922 
3923   /* loop through fields, fetching values */
3924   jsize off = 0;
3925   for (jsize i = 0; i < nfids; i++) {
3926     jfieldID fid = (jfieldID)(intptr_t) fids->long_at(i);
3927     if (fid == NULL) {
3928       THROW(vmSymbols::java_lang_NullPointerException());
3929     }
3930     int field_offset = jfieldIDWorkaround::from_instance_jfieldID(o->klass(), fid);
3931 
3932      switch (tcodes->char_at(i)) {
3933        case 'Z':
3934          {
3935            jboolean val = o->bool_field(field_offset);
3936            dbuf->byte_at_put(off++, (val != 0) ? 1 : 0);
3937          }
3938          break;
3939 
3940        case 'B':
3941          dbuf->byte_at_put(off++, o->byte_field(field_offset));
3942          break;
3943 
3944        case 'C':
3945          {
3946            jchar val = o->char_field(field_offset);
3947            dbuf->byte_at_put(off++, (val >> 8) & 0xFF);
3948            dbuf->byte_at_put(off++, (val >> 0) & 0xFF);
3949          }
3950          break;
3951 
3952        case 'S':
3953          {
3954            jshort val = o->short_field(field_offset);
3955            dbuf->byte_at_put(off++, (val >> 8) & 0xFF);
3956            dbuf->byte_at_put(off++, (val >> 0) & 0xFF);
3957          }
3958          break;
3959 
3960        case 'I':
3961          {
3962            jint val = o->int_field(field_offset);
3963            dbuf->byte_at_put(off++, (val >> 24) & 0xFF);
3964            dbuf->byte_at_put(off++, (val >> 16) & 0xFF);
3965            dbuf->byte_at_put(off++, (val >> 8)  & 0xFF);
3966            dbuf->byte_at_put(off++, (val >> 0)  & 0xFF);
3967          }
3968          break;
3969 
3970        case 'F':
3971          {
3972            jfloat fval = o->float_field(field_offset);
3973            jint ival = (*float_to_int_bits_fn)(env, NULL, fval);
3974            dbuf->byte_at_put(off++, (ival >> 24) & 0xFF);
3975            dbuf->byte_at_put(off++, (ival >> 16) & 0xFF);
3976            dbuf->byte_at_put(off++, (ival >> 8)  & 0xFF);
3977            dbuf->byte_at_put(off++, (ival >> 0)  & 0xFF);
3978          }
3979          break;
3980 
3981        case 'J':
3982          {
3983            jlong val = o->long_field(field_offset);
3984            dbuf->byte_at_put(off++, (val >> 56) & 0xFF);
3985            dbuf->byte_at_put(off++, (val >> 48) & 0xFF);
3986            dbuf->byte_at_put(off++, (val >> 40) & 0xFF);
3987            dbuf->byte_at_put(off++, (val >> 32) & 0xFF);
3988            dbuf->byte_at_put(off++, (val >> 24) & 0xFF);
3989            dbuf->byte_at_put(off++, (val >> 16) & 0xFF);
3990            dbuf->byte_at_put(off++, (val >> 8)  & 0xFF);
3991            dbuf->byte_at_put(off++, (val >> 0)  & 0xFF);
3992          }
3993          break;
3994 
3995        case 'D':
3996          {
3997            jdouble dval = o->double_field(field_offset);
3998            jlong lval = (*double_to_long_bits_fn)(env, NULL, dval);
3999            dbuf->byte_at_put(off++, (lval >> 56) & 0xFF);
4000            dbuf->byte_at_put(off++, (lval >> 48) & 0xFF);
4001            dbuf->byte_at_put(off++, (lval >> 40) & 0xFF);
4002            dbuf->byte_at_put(off++, (lval >> 32) & 0xFF);
4003            dbuf->byte_at_put(off++, (lval >> 24) & 0xFF);
4004            dbuf->byte_at_put(off++, (lval >> 16) & 0xFF);
4005            dbuf->byte_at_put(off++, (lval >> 8)  & 0xFF);
4006            dbuf->byte_at_put(off++, (lval >> 0)  & 0xFF);
4007          }
4008          break;
4009 
4010        default:
4011          // Illegal typecode
4012          THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "illegal typecode");
4013      }
4014   }
4015 JVM_END
4016 
4017 
4018 // Shared JNI/JVM entry points //////////////////////////////////////////////////////////////
4019 
4020 jclass find_class_from_class_loader(JNIEnv* env, Symbol* name, jboolean init, Handle loader, Handle protection_domain, jboolean throwError, TRAPS) {
4021   // Security Note:
4022   //   The Java level wrapper will perform the necessary security check allowing
4023   //   us to pass the NULL as the initiating class loader.
4024   klassOop klass = SystemDictionary::resolve_or_fail(name, loader, protection_domain, throwError != 0, CHECK_NULL);
4025 
4026   KlassHandle klass_handle(THREAD, klass);
4027   // Check if we should initialize the class
4028   if (init && klass_handle->oop_is_instance()) {
4029     klass_handle->initialize(CHECK_NULL);
4030   }
4031   return (jclass) JNIHandles::make_local(env, klass_handle->java_mirror());
4032 }
4033 
4034 
4035 // Internal SQE debugging support ///////////////////////////////////////////////////////////
4036 
4037 #ifndef PRODUCT
4038 
4039 extern "C" {
4040   JNIEXPORT jboolean JNICALL JVM_AccessVMBooleanFlag(const char* name, jboolean* value, jboolean is_get);
4041   JNIEXPORT jboolean JNICALL JVM_AccessVMIntFlag(const char* name, jint* value, jboolean is_get);
4042   JNIEXPORT void JNICALL JVM_VMBreakPoint(JNIEnv *env, jobject obj);
4043 }
4044 
4045 JVM_LEAF(jboolean, JVM_AccessVMBooleanFlag(const char* name, jboolean* value, jboolean is_get))
4046   JVMWrapper("JVM_AccessBoolVMFlag");
4047   return is_get ? CommandLineFlags::boolAt((char*) name, (bool*) value) : CommandLineFlags::boolAtPut((char*) name, (bool*) value, INTERNAL);
4048 JVM_END
4049 
4050 JVM_LEAF(jboolean, JVM_AccessVMIntFlag(const char* name, jint* value, jboolean is_get))
4051   JVMWrapper("JVM_AccessVMIntFlag");
4052   intx v;
4053   jboolean result = is_get ? CommandLineFlags::intxAt((char*) name, &v) : CommandLineFlags::intxAtPut((char*) name, &v, INTERNAL);
4054   *value = (jint)v;
4055   return result;
4056 JVM_END
4057 
4058 
4059 JVM_ENTRY(void, JVM_VMBreakPoint(JNIEnv *env, jobject obj))
4060   JVMWrapper("JVM_VMBreakPoint");
4061   oop the_obj = JNIHandles::resolve(obj);
4062   BREAKPOINT;
4063 JVM_END
4064 
4065 
4066 #endif
4067 
4068 
4069 // Method ///////////////////////////////////////////////////////////////////////////////////////////
4070 
4071 JVM_ENTRY(jobject, JVM_InvokeMethod(JNIEnv *env, jobject method, jobject obj, jobjectArray args0))
4072   JVMWrapper("JVM_InvokeMethod");
4073   Handle method_handle;
4074   if (thread->stack_available((address) &method_handle) >= JVMInvokeMethodSlack) {
4075     method_handle = Handle(THREAD, JNIHandles::resolve(method));
4076     Handle receiver(THREAD, JNIHandles::resolve(obj));
4077     objArrayHandle args(THREAD, objArrayOop(JNIHandles::resolve(args0)));
4078     oop result = Reflection::invoke_method(method_handle(), receiver, args, CHECK_NULL);
4079     jobject res = JNIHandles::make_local(env, result);
4080     if (JvmtiExport::should_post_vm_object_alloc()) {
4081       oop ret_type = java_lang_reflect_Method::return_type(method_handle());
4082       assert(ret_type != NULL, "sanity check: ret_type oop must not be NULL!");
4083       if (java_lang_Class::is_primitive(ret_type)) {
4084         // Only for primitive type vm allocates memory for java object.
4085         // See box() method.
4086         JvmtiExport::post_vm_object_alloc(JavaThread::current(), result);
4087       }
4088     }
4089     return res;
4090   } else {
4091     THROW_0(vmSymbols::java_lang_StackOverflowError());
4092   }
4093 JVM_END
4094 
4095 
4096 JVM_ENTRY(jobject, JVM_NewInstanceFromConstructor(JNIEnv *env, jobject c, jobjectArray args0))
4097   JVMWrapper("JVM_NewInstanceFromConstructor");
4098   oop constructor_mirror = JNIHandles::resolve(c);
4099   objArrayHandle args(THREAD, objArrayOop(JNIHandles::resolve(args0)));
4100   oop result = Reflection::invoke_constructor(constructor_mirror, args, CHECK_NULL);
4101   jobject res = JNIHandles::make_local(env, result);
4102   if (JvmtiExport::should_post_vm_object_alloc()) {
4103     JvmtiExport::post_vm_object_alloc(JavaThread::current(), result);
4104   }
4105   return res;
4106 JVM_END
4107 
4108 // Atomic ///////////////////////////////////////////////////////////////////////////////////////////
4109 
4110 JVM_LEAF(jboolean, JVM_SupportsCX8())
4111   JVMWrapper("JVM_SupportsCX8");
4112   return VM_Version::supports_cx8();
4113 JVM_END
4114 
4115 
4116 JVM_ENTRY(jboolean, JVM_CX8Field(JNIEnv *env, jobject obj, jfieldID fid, jlong oldVal, jlong newVal))
4117   JVMWrapper("JVM_CX8Field");
4118   jlong res;
4119   oop             o       = JNIHandles::resolve(obj);
4120   intptr_t        fldOffs = jfieldIDWorkaround::from_instance_jfieldID(o->klass(), fid);
4121   volatile jlong* addr    = (volatile jlong*)((address)o + fldOffs);
4122 
4123   assert(VM_Version::supports_cx8(), "cx8 not supported");
4124   res = Atomic::cmpxchg(newVal, addr, oldVal);
4125 
4126   return res == oldVal;
4127 JVM_END
4128 
4129 // DTrace ///////////////////////////////////////////////////////////////////
4130 
4131 JVM_ENTRY(jint, JVM_DTraceGetVersion(JNIEnv* env))
4132   JVMWrapper("JVM_DTraceGetVersion");
4133   return (jint)JVM_TRACING_DTRACE_VERSION;
4134 JVM_END
4135 
4136 JVM_ENTRY(jlong,JVM_DTraceActivate(
4137     JNIEnv* env, jint version, jstring module_name, jint providers_count,
4138     JVM_DTraceProvider* providers))
4139   JVMWrapper("JVM_DTraceActivate");
4140   return DTraceJSDT::activate(
4141     version, module_name, providers_count, providers, CHECK_0);
4142 JVM_END
4143 
4144 JVM_ENTRY(jboolean,JVM_DTraceIsProbeEnabled(JNIEnv* env, jmethodID method))
4145   JVMWrapper("JVM_DTraceIsProbeEnabled");
4146   return DTraceJSDT::is_probe_enabled(method);
4147 JVM_END
4148 
4149 JVM_ENTRY(void,JVM_DTraceDispose(JNIEnv* env, jlong handle))
4150   JVMWrapper("JVM_DTraceDispose");
4151   DTraceJSDT::dispose(handle);
4152 JVM_END
4153 
4154 JVM_ENTRY(jboolean,JVM_DTraceIsSupported(JNIEnv* env))
4155   JVMWrapper("JVM_DTraceIsSupported");
4156   return DTraceJSDT::is_supported();
4157 JVM_END
4158 
4159 // Returns an array of all live Thread objects (VM internal JavaThreads,
4160 // jvmti agent threads, and JNI attaching threads  are skipped)
4161 // See CR 6404306 regarding JNI attaching threads
4162 JVM_ENTRY(jobjectArray, JVM_GetAllThreads(JNIEnv *env, jclass dummy))
4163   ResourceMark rm(THREAD);
4164   ThreadsListEnumerator tle(THREAD, false, false);
4165   JvmtiVMObjectAllocEventCollector oam;
4166 
4167   int num_threads = tle.num_threads();
4168   objArrayOop r = oopFactory::new_objArray(SystemDictionary::Thread_klass(), num_threads, CHECK_NULL);
4169   objArrayHandle threads_ah(THREAD, r);
4170 
4171   for (int i = 0; i < num_threads; i++) {
4172     Handle h = tle.get_threadObj(i);
4173     threads_ah->obj_at_put(i, h());
4174   }
4175 
4176   return (jobjectArray) JNIHandles::make_local(env, threads_ah());
4177 JVM_END
4178 
4179 
4180 // Support for java.lang.Thread.getStackTrace() and getAllStackTraces() methods
4181 // Return StackTraceElement[][], each element is the stack trace of a thread in
4182 // the corresponding entry in the given threads array
4183 JVM_ENTRY(jobjectArray, JVM_DumpThreads(JNIEnv *env, jclass threadClass, jobjectArray threads))
4184   JVMWrapper("JVM_DumpThreads");
4185   JvmtiVMObjectAllocEventCollector oam;
4186 
4187   // Check if threads is null
4188   if (threads == NULL) {
4189     THROW_(vmSymbols::java_lang_NullPointerException(), 0);
4190   }
4191 
4192   objArrayOop a = objArrayOop(JNIHandles::resolve_non_null(threads));
4193   objArrayHandle ah(THREAD, a);
4194   int num_threads = ah->length();
4195   // check if threads is non-empty array
4196   if (num_threads == 0) {
4197     THROW_(vmSymbols::java_lang_IllegalArgumentException(), 0);
4198   }
4199 
4200   // check if threads is not an array of objects of Thread class
4201   klassOop k = objArrayKlass::cast(ah->klass())->element_klass();
4202   if (k != SystemDictionary::Thread_klass()) {
4203     THROW_(vmSymbols::java_lang_IllegalArgumentException(), 0);
4204   }
4205 
4206   ResourceMark rm(THREAD);
4207 
4208   GrowableArray<instanceHandle>* thread_handle_array = new GrowableArray<instanceHandle>(num_threads);
4209   for (int i = 0; i < num_threads; i++) {
4210     oop thread_obj = ah->obj_at(i);
4211     instanceHandle h(THREAD, (instanceOop) thread_obj);
4212     thread_handle_array->append(h);
4213   }
4214 
4215   Handle stacktraces = ThreadService::dump_stack_traces(thread_handle_array, num_threads, CHECK_NULL);
4216   return (jobjectArray)JNIHandles::make_local(env, stacktraces());
4217 
4218 JVM_END
4219 
4220 // JVM monitoring and management support
4221 JVM_ENTRY_NO_ENV(void*, JVM_GetManagement(jint version))
4222   return Management::get_jmm_interface(version);
4223 JVM_END
4224 
4225 // com.sun.tools.attach.VirtualMachine agent properties support
4226 //
4227 // Initialize the agent properties with the properties maintained in the VM
4228 JVM_ENTRY(jobject, JVM_InitAgentProperties(JNIEnv *env, jobject properties))
4229   JVMWrapper("JVM_InitAgentProperties");
4230   ResourceMark rm;
4231 
4232   Handle props(THREAD, JNIHandles::resolve_non_null(properties));
4233 
4234   PUTPROP(props, "sun.java.command", Arguments::java_command());
4235   PUTPROP(props, "sun.jvm.flags", Arguments::jvm_flags());
4236   PUTPROP(props, "sun.jvm.args", Arguments::jvm_args());
4237   return properties;
4238 JVM_END
4239 
4240 JVM_ENTRY(jobjectArray, JVM_GetEnclosingMethodInfo(JNIEnv *env, jclass ofClass))
4241 {
4242   JVMWrapper("JVM_GetEnclosingMethodInfo");
4243   JvmtiVMObjectAllocEventCollector oam;
4244 
4245   if (ofClass == NULL) {
4246     return NULL;
4247   }
4248   Handle mirror(THREAD, JNIHandles::resolve_non_null(ofClass));
4249   // Special handling for primitive objects
4250   if (java_lang_Class::is_primitive(mirror())) {
4251     return NULL;
4252   }
4253   klassOop k = java_lang_Class::as_klassOop(mirror());
4254   if (!Klass::cast(k)->oop_is_instance()) {
4255     return NULL;
4256   }
4257   instanceKlassHandle ik_h(THREAD, k);
4258   int encl_method_class_idx = ik_h->enclosing_method_class_index();
4259   if (encl_method_class_idx == 0) {
4260     return NULL;
4261   }
4262   objArrayOop dest_o = oopFactory::new_objArray(SystemDictionary::Object_klass(), 3, CHECK_NULL);
4263   objArrayHandle dest(THREAD, dest_o);
4264   klassOop enc_k = ik_h->constants()->klass_at(encl_method_class_idx, CHECK_NULL);
4265   dest->obj_at_put(0, Klass::cast(enc_k)->java_mirror());
4266   int encl_method_method_idx = ik_h->enclosing_method_method_index();
4267   if (encl_method_method_idx != 0) {
4268     Symbol* sym = ik_h->constants()->symbol_at(
4269                         extract_low_short_from_int(
4270                           ik_h->constants()->name_and_type_at(encl_method_method_idx)));
4271     Handle str = java_lang_String::create_from_symbol(sym, CHECK_NULL);
4272     dest->obj_at_put(1, str());
4273     sym = ik_h->constants()->symbol_at(
4274               extract_high_short_from_int(
4275                 ik_h->constants()->name_and_type_at(encl_method_method_idx)));
4276     str = java_lang_String::create_from_symbol(sym, CHECK_NULL);
4277     dest->obj_at_put(2, str());
4278   }
4279   return (jobjectArray) JNIHandles::make_local(dest());
4280 }
4281 JVM_END
4282 
4283 JVM_ENTRY(jintArray, JVM_GetThreadStateValues(JNIEnv* env,
4284                                               jint javaThreadState))
4285 {
4286   // If new thread states are added in future JDK and VM versions,
4287   // this should check if the JDK version is compatible with thread
4288   // states supported by the VM.  Return NULL if not compatible.
4289   //
4290   // This function must map the VM java_lang_Thread::ThreadStatus
4291   // to the Java thread state that the JDK supports.
4292   //
4293 
4294   typeArrayHandle values_h;
4295   switch (javaThreadState) {
4296     case JAVA_THREAD_STATE_NEW : {
4297       typeArrayOop r = oopFactory::new_typeArray(T_INT, 1, CHECK_NULL);
4298       values_h = typeArrayHandle(THREAD, r);
4299       values_h->int_at_put(0, java_lang_Thread::NEW);
4300       break;
4301     }
4302     case JAVA_THREAD_STATE_RUNNABLE : {
4303       typeArrayOop r = oopFactory::new_typeArray(T_INT, 1, CHECK_NULL);
4304       values_h = typeArrayHandle(THREAD, r);
4305       values_h->int_at_put(0, java_lang_Thread::RUNNABLE);
4306       break;
4307     }
4308     case JAVA_THREAD_STATE_BLOCKED : {
4309       typeArrayOop r = oopFactory::new_typeArray(T_INT, 1, CHECK_NULL);
4310       values_h = typeArrayHandle(THREAD, r);
4311       values_h->int_at_put(0, java_lang_Thread::BLOCKED_ON_MONITOR_ENTER);
4312       break;
4313     }
4314     case JAVA_THREAD_STATE_WAITING : {
4315       typeArrayOop r = oopFactory::new_typeArray(T_INT, 2, CHECK_NULL);
4316       values_h = typeArrayHandle(THREAD, r);
4317       values_h->int_at_put(0, java_lang_Thread::IN_OBJECT_WAIT);
4318       values_h->int_at_put(1, java_lang_Thread::PARKED);
4319       break;
4320     }
4321     case JAVA_THREAD_STATE_TIMED_WAITING : {
4322       typeArrayOop r = oopFactory::new_typeArray(T_INT, 3, CHECK_NULL);
4323       values_h = typeArrayHandle(THREAD, r);
4324       values_h->int_at_put(0, java_lang_Thread::SLEEPING);
4325       values_h->int_at_put(1, java_lang_Thread::IN_OBJECT_WAIT_TIMED);
4326       values_h->int_at_put(2, java_lang_Thread::PARKED_TIMED);
4327       break;
4328     }
4329     case JAVA_THREAD_STATE_TERMINATED : {
4330       typeArrayOop r = oopFactory::new_typeArray(T_INT, 1, CHECK_NULL);
4331       values_h = typeArrayHandle(THREAD, r);
4332       values_h->int_at_put(0, java_lang_Thread::TERMINATED);
4333       break;
4334     }
4335     default:
4336       // Unknown state - probably incompatible JDK version
4337       return NULL;
4338   }
4339 
4340   return (jintArray) JNIHandles::make_local(env, values_h());
4341 }
4342 JVM_END
4343 
4344 
4345 JVM_ENTRY(jobjectArray, JVM_GetThreadStateNames(JNIEnv* env,
4346                                                 jint javaThreadState,
4347                                                 jintArray values))
4348 {
4349   // If new thread states are added in future JDK and VM versions,
4350   // this should check if the JDK version is compatible with thread
4351   // states supported by the VM.  Return NULL if not compatible.
4352   //
4353   // This function must map the VM java_lang_Thread::ThreadStatus
4354   // to the Java thread state that the JDK supports.
4355   //
4356 
4357   ResourceMark rm;
4358 
4359   // Check if threads is null
4360   if (values == NULL) {
4361     THROW_(vmSymbols::java_lang_NullPointerException(), 0);
4362   }
4363 
4364   typeArrayOop v = typeArrayOop(JNIHandles::resolve_non_null(values));
4365   typeArrayHandle values_h(THREAD, v);
4366 
4367   objArrayHandle names_h;
4368   switch (javaThreadState) {
4369     case JAVA_THREAD_STATE_NEW : {
4370       assert(values_h->length() == 1 &&
4371                values_h->int_at(0) == java_lang_Thread::NEW,
4372              "Invalid threadStatus value");
4373 
4374       objArrayOop r = oopFactory::new_objArray(SystemDictionary::String_klass(),
4375                                                1, /* only 1 substate */
4376                                                CHECK_NULL);
4377       names_h = objArrayHandle(THREAD, r);
4378       Handle name = java_lang_String::create_from_str("NEW", CHECK_NULL);
4379       names_h->obj_at_put(0, name());
4380       break;
4381     }
4382     case JAVA_THREAD_STATE_RUNNABLE : {
4383       assert(values_h->length() == 1 &&
4384                values_h->int_at(0) == java_lang_Thread::RUNNABLE,
4385              "Invalid threadStatus value");
4386 
4387       objArrayOop r = oopFactory::new_objArray(SystemDictionary::String_klass(),
4388                                                1, /* only 1 substate */
4389                                                CHECK_NULL);
4390       names_h = objArrayHandle(THREAD, r);
4391       Handle name = java_lang_String::create_from_str("RUNNABLE", CHECK_NULL);
4392       names_h->obj_at_put(0, name());
4393       break;
4394     }
4395     case JAVA_THREAD_STATE_BLOCKED : {
4396       assert(values_h->length() == 1 &&
4397                values_h->int_at(0) == java_lang_Thread::BLOCKED_ON_MONITOR_ENTER,
4398              "Invalid threadStatus value");
4399 
4400       objArrayOop r = oopFactory::new_objArray(SystemDictionary::String_klass(),
4401                                                1, /* only 1 substate */
4402                                                CHECK_NULL);
4403       names_h = objArrayHandle(THREAD, r);
4404       Handle name = java_lang_String::create_from_str("BLOCKED", CHECK_NULL);
4405       names_h->obj_at_put(0, name());
4406       break;
4407     }
4408     case JAVA_THREAD_STATE_WAITING : {
4409       assert(values_h->length() == 2 &&
4410                values_h->int_at(0) == java_lang_Thread::IN_OBJECT_WAIT &&
4411                values_h->int_at(1) == java_lang_Thread::PARKED,
4412              "Invalid threadStatus value");
4413       objArrayOop r = oopFactory::new_objArray(SystemDictionary::String_klass(),
4414                                                2, /* number of substates */
4415                                                CHECK_NULL);
4416       names_h = objArrayHandle(THREAD, r);
4417       Handle name0 = java_lang_String::create_from_str("WAITING.OBJECT_WAIT",
4418                                                        CHECK_NULL);
4419       Handle name1 = java_lang_String::create_from_str("WAITING.PARKED",
4420                                                        CHECK_NULL);
4421       names_h->obj_at_put(0, name0());
4422       names_h->obj_at_put(1, name1());
4423       break;
4424     }
4425     case JAVA_THREAD_STATE_TIMED_WAITING : {
4426       assert(values_h->length() == 3 &&
4427                values_h->int_at(0) == java_lang_Thread::SLEEPING &&
4428                values_h->int_at(1) == java_lang_Thread::IN_OBJECT_WAIT_TIMED &&
4429                values_h->int_at(2) == java_lang_Thread::PARKED_TIMED,
4430              "Invalid threadStatus value");
4431       objArrayOop r = oopFactory::new_objArray(SystemDictionary::String_klass(),
4432                                                3, /* number of substates */
4433                                                CHECK_NULL);
4434       names_h = objArrayHandle(THREAD, r);
4435       Handle name0 = java_lang_String::create_from_str("TIMED_WAITING.SLEEPING",
4436                                                        CHECK_NULL);
4437       Handle name1 = java_lang_String::create_from_str("TIMED_WAITING.OBJECT_WAIT",
4438                                                        CHECK_NULL);
4439       Handle name2 = java_lang_String::create_from_str("TIMED_WAITING.PARKED",
4440                                                        CHECK_NULL);
4441       names_h->obj_at_put(0, name0());
4442       names_h->obj_at_put(1, name1());
4443       names_h->obj_at_put(2, name2());
4444       break;
4445     }
4446     case JAVA_THREAD_STATE_TERMINATED : {
4447       assert(values_h->length() == 1 &&
4448                values_h->int_at(0) == java_lang_Thread::TERMINATED,
4449              "Invalid threadStatus value");
4450       objArrayOop r = oopFactory::new_objArray(SystemDictionary::String_klass(),
4451                                                1, /* only 1 substate */
4452                                                CHECK_NULL);
4453       names_h = objArrayHandle(THREAD, r);
4454       Handle name = java_lang_String::create_from_str("TERMINATED", CHECK_NULL);
4455       names_h->obj_at_put(0, name());
4456       break;
4457     }
4458     default:
4459       // Unknown state - probably incompatible JDK version
4460       return NULL;
4461   }
4462   return (jobjectArray) JNIHandles::make_local(env, names_h());
4463 }
4464 JVM_END
4465 
4466 JVM_ENTRY(void, JVM_GetVersionInfo(JNIEnv* env, jvm_version_info* info, size_t info_size))
4467 {
4468   memset(info, 0, sizeof(info_size));
4469 
4470   info->jvm_version = Abstract_VM_Version::jvm_version();
4471   info->update_version = 0;          /* 0 in HotSpot Express VM */
4472   info->special_update_version = 0;  /* 0 in HotSpot Express VM */
4473 
4474   // when we add a new capability in the jvm_version_info struct, we should also
4475   // consider to expose this new capability in the sun.rt.jvmCapabilities jvmstat
4476   // counter defined in runtimeService.cpp.
4477   info->is_attachable = AttachListener::is_attach_supported();
4478 #ifdef KERNEL
4479   info->is_kernel_jvm = 1; // true;
4480 #else  // KERNEL
4481   info->is_kernel_jvm = 0; // false;
4482 #endif // KERNEL
4483 }
4484 JVM_END