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