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