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