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