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