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