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