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