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 //
 704 // Rationale behind JVM_FindClassFromBootLoader
 705 // a> JVM_FindClassFromClassLoader was never exported in the export tables.
 706 // b> because of (a) java.dll has a direct dependecy on the  unexported
 707 //    private symbol "_JVM_FindClassFromClassLoader@20".
 708 // c> the launcher cannot use the private symbol as it dynamically opens
 709 //    the entry point, so if something changes, the launcher will fail
 710 //    unexpectedly at runtime, it is safest for the launcher to dlopen a
 711 //    stable exported interface.
 712 // d> re-exporting JVM_FindClassFromClassLoader as public, will cause its
 713 //    signature to change from _JVM_FindClassFromClassLoader@20 to
 714 //    JVM_FindClassFromClassLoader and will not be backward compatible
 715 //    with older JDKs.
 716 // Thus a public/stable exported entry point is the right solution,
 717 // public here means public in linker semantics, and is exported only
 718 // to the JDK, and is not intended to be a public API.
 719 
 720 JVM_ENTRY(jclass, JVM_FindClassFromBootLoader(JNIEnv* env,
 721                                               const char* name))
 722   JVMWrapper2("JVM_FindClassFromBootLoader %s", name);
 723 
 724   // Java libraries should ensure that name is never null...
 725   if (name == NULL || (int)strlen(name) > Symbol::max_length()) {
 726     // It's impossible to create this class;  the name cannot fit
 727     // into the constant pool.
 728     return NULL;
 729   }
 730 
 731   TempNewSymbol h_name = SymbolTable::new_symbol(name, CHECK_NULL);
 732   Klass* k = SystemDictionary::resolve_or_null(h_name, CHECK_NULL);
 733   if (k == NULL) {
 734     return NULL;
 735   }
 736 
 737   if (TraceClassResolution) {
 738     trace_class_resolution(k);
 739   }
 740   return (jclass) JNIHandles::make_local(env, k->java_mirror());
 741 JVM_END
 742 
 743 // Not used; JVM_FindClassFromCaller replaces this.
 744 JVM_ENTRY(jclass, JVM_FindClassFromClassLoader(JNIEnv* env, const char* name,
 745                                                jboolean init, jobject loader,
 746                                                jboolean throwError))
 747   JVMWrapper3("JVM_FindClassFromClassLoader %s throw %s", name,
 748                throwError ? "error" : "exception");
 749   // Java libraries should ensure that name is never null...
 750   if (name == NULL || (int)strlen(name) > Symbol::max_length()) {
 751     // It's impossible to create this class;  the name cannot fit
 752     // into the constant pool.
 753     if (throwError) {
 754       THROW_MSG_0(vmSymbols::java_lang_NoClassDefFoundError(), name);
 755     } else {
 756       THROW_MSG_0(vmSymbols::java_lang_ClassNotFoundException(), name);
 757     }
 758   }
 759   TempNewSymbol h_name = SymbolTable::new_symbol(name, CHECK_NULL);
 760   Handle h_loader(THREAD, JNIHandles::resolve(loader));
 761   jclass result = find_class_from_class_loader(env, h_name, init, h_loader,
 762                                                Handle(), throwError, THREAD);
 763 
 764   if (TraceClassResolution && result != NULL) {
 765     trace_class_resolution(java_lang_Class::as_Klass(JNIHandles::resolve_non_null(result)));
 766   }
 767   return result;
 768 JVM_END
 769 
 770 // Find a class with this name in this loader, using the caller's protection domain.
 771 JVM_ENTRY(jclass, JVM_FindClassFromCaller(JNIEnv* env, const char* name,
 772                                           jboolean init, jobject loader,
 773                                           jclass caller))
 774   JVMWrapper2("JVM_FindClassFromCaller %s throws ClassNotFoundException", name);
 775   // Java libraries should ensure that name is never null...
 776   if (name == NULL || (int)strlen(name) > Symbol::max_length()) {
 777     // It's impossible to create this class;  the name cannot fit
 778     // into the constant pool.
 779     THROW_MSG_0(vmSymbols::java_lang_ClassNotFoundException(), name);
 780   }
 781 
 782   TempNewSymbol h_name = SymbolTable::new_symbol(name, CHECK_NULL);
 783 
 784   oop loader_oop = JNIHandles::resolve(loader);
 785   oop from_class = JNIHandles::resolve(caller);
 786   oop protection_domain = NULL;
 787   // If loader is null, shouldn't call ClassLoader.checkPackageAccess; otherwise get
 788   // NPE. Put it in another way, the bootstrap class loader has all permission and
 789   // thus no checkPackageAccess equivalence in the VM class loader.
 790   // The caller is also passed as NULL by the java code if there is no security
 791   // manager to avoid the performance cost of getting the calling class.
 792   if (from_class != NULL && loader_oop != NULL) {
 793     protection_domain = java_lang_Class::as_Klass(from_class)->protection_domain();
 794   }
 795 
 796   Handle h_loader(THREAD, loader_oop);
 797   Handle h_prot(THREAD, protection_domain);
 798   jclass result = find_class_from_class_loader(env, h_name, init, h_loader,
 799                                                h_prot, false, THREAD);
 800 
 801   if (TraceClassResolution && result != NULL) {
 802     trace_class_resolution(java_lang_Class::as_Klass(JNIHandles::resolve_non_null(result)));
 803   }
 804   return result;
 805 JVM_END
 806 
 807 JVM_ENTRY(jclass, JVM_FindClassFromClass(JNIEnv *env, const char *name,
 808                                          jboolean init, jclass from))
 809   JVMWrapper2("JVM_FindClassFromClass %s", name);
 810   if (name == NULL || (int)strlen(name) > Symbol::max_length()) {
 811     // It's impossible to create this class;  the name cannot fit
 812     // into the constant pool.
 813     THROW_MSG_0(vmSymbols::java_lang_NoClassDefFoundError(), name);
 814   }
 815   TempNewSymbol h_name = SymbolTable::new_symbol(name, CHECK_NULL);
 816   oop from_class_oop = JNIHandles::resolve(from);
 817   Klass* from_class = (from_class_oop == NULL)
 818                            ? (Klass*)NULL
 819                            : java_lang_Class::as_Klass(from_class_oop);
 820   oop class_loader = NULL;
 821   oop protection_domain = NULL;
 822   if (from_class != NULL) {
 823     class_loader = from_class->class_loader();
 824     protection_domain = from_class->protection_domain();
 825   }
 826   Handle h_loader(THREAD, class_loader);
 827   Handle h_prot  (THREAD, protection_domain);
 828   jclass result = find_class_from_class_loader(env, h_name, init, h_loader,
 829                                                h_prot, true, thread);
 830 
 831   if (TraceClassResolution && result != NULL) {
 832     // this function is generally only used for class loading during verification.
 833     ResourceMark rm;
 834     oop from_mirror = JNIHandles::resolve_non_null(from);
 835     Klass* from_class = java_lang_Class::as_Klass(from_mirror);
 836     const char * from_name = from_class->external_name();
 837 
 838     oop mirror = JNIHandles::resolve_non_null(result);
 839     Klass* to_class = java_lang_Class::as_Klass(mirror);
 840     const char * to = to_class->external_name();
 841     tty->print("RESOLVE %s %s (verification)\n", from_name, to);
 842   }
 843 
 844   return result;
 845 JVM_END
 846 
 847 static void is_lock_held_by_thread(Handle loader, PerfCounter* counter, TRAPS) {
 848   if (loader.is_null()) {
 849     return;
 850   }
 851 
 852   // check whether the current caller thread holds the lock or not.
 853   // If not, increment the corresponding counter
 854   if (ObjectSynchronizer::query_lock_ownership((JavaThread*)THREAD, loader) !=
 855       ObjectSynchronizer::owner_self) {
 856     counter->inc();
 857   }
 858 }
 859 
 860 // common code for JVM_DefineClass() and JVM_DefineClassWithSource()
 861 // and JVM_DefineClassWithSourceCond()
 862 static jclass jvm_define_class_common(JNIEnv *env, const char *name,
 863                                       jobject loader, const jbyte *buf,
 864                                       jsize len, jobject pd, const char *source,
 865                                       jboolean verify, TRAPS) {
 866   if (source == NULL)  source = "__JVM_DefineClass__";
 867 
 868   assert(THREAD->is_Java_thread(), "must be a JavaThread");
 869   JavaThread* jt = (JavaThread*) THREAD;
 870 
 871   PerfClassTraceTime vmtimer(ClassLoader::perf_define_appclass_time(),
 872                              ClassLoader::perf_define_appclass_selftime(),
 873                              ClassLoader::perf_define_appclasses(),
 874                              jt->get_thread_stat()->perf_recursion_counts_addr(),
 875                              jt->get_thread_stat()->perf_timers_addr(),
 876                              PerfClassTraceTime::DEFINE_CLASS);
 877 
 878   if (UsePerfData) {
 879     ClassLoader::perf_app_classfile_bytes_read()->inc(len);
 880   }
 881 
 882   // Since exceptions can be thrown, class initialization can take place
 883   // if name is NULL no check for class name in .class stream has to be made.
 884   TempNewSymbol class_name = NULL;
 885   if (name != NULL) {
 886     const int str_len = (int)strlen(name);
 887     if (str_len > Symbol::max_length()) {
 888       // It's impossible to create this class;  the name cannot fit
 889       // into the constant pool.
 890       THROW_MSG_0(vmSymbols::java_lang_NoClassDefFoundError(), name);
 891     }
 892     class_name = SymbolTable::new_symbol(name, str_len, CHECK_NULL);
 893   }
 894 
 895   ResourceMark rm(THREAD);
 896   ClassFileStream st((u1*) buf, len, (char *)source);
 897   Handle class_loader (THREAD, JNIHandles::resolve(loader));
 898   if (UsePerfData) {
 899     is_lock_held_by_thread(class_loader,
 900                            ClassLoader::sync_JVMDefineClassLockFreeCounter(),
 901                            THREAD);
 902   }
 903   Handle protection_domain (THREAD, JNIHandles::resolve(pd));
 904   Klass* k = SystemDictionary::resolve_from_stream(class_name, class_loader,
 905                                                      protection_domain, &st,
 906                                                      verify != 0,
 907                                                      CHECK_NULL);
 908 
 909   if (TraceClassResolution && k != NULL) {
 910     trace_class_resolution(k);
 911   }
 912 
 913   return (jclass) JNIHandles::make_local(env, k->java_mirror());
 914 }
 915 
 916 
 917 JVM_ENTRY(jclass, JVM_DefineClass(JNIEnv *env, const char *name, jobject loader, const jbyte *buf, jsize len, jobject pd))
 918   JVMWrapper2("JVM_DefineClass %s", name);
 919 
 920   return jvm_define_class_common(env, name, loader, buf, len, pd, NULL, true, THREAD);
 921 JVM_END
 922 
 923 
 924 JVM_ENTRY(jclass, JVM_DefineClassWithSource(JNIEnv *env, const char *name, jobject loader, const jbyte *buf, jsize len, jobject pd, const char *source))
 925   JVMWrapper2("JVM_DefineClassWithSource %s", name);
 926 
 927   return jvm_define_class_common(env, name, loader, buf, len, pd, source, true, THREAD);
 928 JVM_END
 929 
 930 JVM_ENTRY(jclass, JVM_DefineClassWithSourceCond(JNIEnv *env, const char *name,
 931                                                 jobject loader, const jbyte *buf,
 932                                                 jsize len, jobject pd,
 933                                                 const char *source, jboolean verify))
 934   JVMWrapper2("JVM_DefineClassWithSourceCond %s", name);
 935 
 936   return jvm_define_class_common(env, name, loader, buf, len, pd, source, verify, THREAD);
 937 JVM_END
 938 
 939 JVM_ENTRY(jclass, JVM_FindLoadedClass(JNIEnv *env, jobject loader, jstring name))
 940   JVMWrapper("JVM_FindLoadedClass");
 941   ResourceMark rm(THREAD);
 942 
 943   Handle h_name (THREAD, JNIHandles::resolve_non_null(name));
 944   Handle string = java_lang_String::internalize_classname(h_name, CHECK_NULL);
 945 
 946   const char* str   = java_lang_String::as_utf8_string(string());
 947   // Sanity check, don't expect null
 948   if (str == NULL) return NULL;
 949 
 950   const int str_len = (int)strlen(str);
 951   if (str_len > Symbol::max_length()) {
 952     // It's impossible to create this class;  the name cannot fit
 953     // into the constant pool.
 954     return NULL;
 955   }
 956   TempNewSymbol klass_name = SymbolTable::new_symbol(str, str_len, CHECK_NULL);
 957 
 958   // Security Note:
 959   //   The Java level wrapper will perform the necessary security check allowing
 960   //   us to pass the NULL as the initiating class loader.
 961   Handle h_loader(THREAD, JNIHandles::resolve(loader));
 962   if (UsePerfData) {
 963     is_lock_held_by_thread(h_loader,
 964                            ClassLoader::sync_JVMFindLoadedClassLockFreeCounter(),
 965                            THREAD);
 966   }
 967 
 968   Klass* k = SystemDictionary::find_instance_or_array_klass(klass_name,
 969                                                               h_loader,
 970                                                               Handle(),
 971                                                               CHECK_NULL);
 972 #if INCLUDE_CDS
 973   if (k == NULL) {
 974     // If the class is not already loaded, try to see if it's in the shared
 975     // archive for the current classloader (h_loader).
 976     instanceKlassHandle ik = SystemDictionaryShared::find_or_load_shared_class(
 977         klass_name, h_loader, CHECK_NULL);
 978     k = ik();
 979   }
 980 #endif
 981   return (k == NULL) ? NULL :
 982             (jclass) JNIHandles::make_local(env, k->java_mirror());
 983 JVM_END
 984 
 985 
 986 // Reflection support //////////////////////////////////////////////////////////////////////////////
 987 
 988 JVM_ENTRY(jstring, JVM_GetClassName(JNIEnv *env, jclass cls))
 989   assert (cls != NULL, "illegal class");
 990   JVMWrapper("JVM_GetClassName");
 991   JvmtiVMObjectAllocEventCollector oam;
 992   ResourceMark rm(THREAD);
 993   const char* name;
 994   if (java_lang_Class::is_primitive(JNIHandles::resolve(cls))) {
 995     name = type2name(java_lang_Class::primitive_type(JNIHandles::resolve(cls)));
 996   } else {
 997     // Consider caching interned string in Klass
 998     Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve(cls));
 999     assert(k->is_klass(), "just checking");
1000     name = k->external_name();
1001   }
1002   oop result = StringTable::intern((char*) name, CHECK_NULL);
1003   return (jstring) JNIHandles::make_local(env, result);
1004 JVM_END
1005 
1006 
1007 JVM_ENTRY(jobjectArray, JVM_GetClassInterfaces(JNIEnv *env, jclass cls))
1008   JVMWrapper("JVM_GetClassInterfaces");
1009   JvmtiVMObjectAllocEventCollector oam;
1010   oop mirror = JNIHandles::resolve_non_null(cls);
1011 
1012   // Special handling for primitive objects
1013   if (java_lang_Class::is_primitive(mirror)) {
1014     // Primitive objects does not have any interfaces
1015     objArrayOop r = oopFactory::new_objArray(SystemDictionary::Class_klass(), 0, CHECK_NULL);
1016     return (jobjectArray) JNIHandles::make_local(env, r);
1017   }
1018 
1019   KlassHandle klass(thread, java_lang_Class::as_Klass(mirror));
1020   // Figure size of result array
1021   int size;
1022   if (klass->oop_is_instance()) {
1023     size = InstanceKlass::cast(klass())->local_interfaces()->length();
1024   } else {
1025     assert(klass->oop_is_objArray() || klass->oop_is_typeArray(), "Illegal mirror klass");
1026     size = 2;
1027   }
1028 
1029   // Allocate result array
1030   objArrayOop r = oopFactory::new_objArray(SystemDictionary::Class_klass(), size, CHECK_NULL);
1031   objArrayHandle result (THREAD, r);
1032   // Fill in result
1033   if (klass->oop_is_instance()) {
1034     // Regular instance klass, fill in all local interfaces
1035     for (int index = 0; index < size; index++) {
1036       Klass* k = InstanceKlass::cast(klass())->local_interfaces()->at(index);
1037       result->obj_at_put(index, k->java_mirror());
1038     }
1039   } else {
1040     // All arrays implement java.lang.Cloneable and java.io.Serializable
1041     result->obj_at_put(0, SystemDictionary::Cloneable_klass()->java_mirror());
1042     result->obj_at_put(1, SystemDictionary::Serializable_klass()->java_mirror());
1043   }
1044   return (jobjectArray) JNIHandles::make_local(env, result());
1045 JVM_END
1046 
1047 
1048 JVM_QUICK_ENTRY(jboolean, JVM_IsInterface(JNIEnv *env, jclass cls))
1049   JVMWrapper("JVM_IsInterface");
1050   oop mirror = JNIHandles::resolve_non_null(cls);
1051   if (java_lang_Class::is_primitive(mirror)) {
1052     return JNI_FALSE;
1053   }
1054   Klass* k = java_lang_Class::as_Klass(mirror);
1055   jboolean result = k->is_interface();
1056   assert(!result || k->oop_is_instance(),
1057          "all interfaces are instance types");
1058   // The compiler intrinsic for isInterface tests the
1059   // Klass::_access_flags bits in the same way.
1060   return result;
1061 JVM_END
1062 
1063 
1064 JVM_ENTRY(jobjectArray, JVM_GetClassSigners(JNIEnv *env, jclass cls))
1065   JVMWrapper("JVM_GetClassSigners");
1066   JvmtiVMObjectAllocEventCollector oam;
1067   if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(cls))) {
1068     // There are no signers for primitive types
1069     return NULL;
1070   }
1071 
1072   objArrayOop signers = java_lang_Class::signers(JNIHandles::resolve_non_null(cls));
1073 
1074   // If there are no signers set in the class, or if the class
1075   // is an array, return NULL.
1076   if (signers == NULL) return NULL;
1077 
1078   // copy of the signers array
1079   Klass* element = ObjArrayKlass::cast(signers->klass())->element_klass();
1080   objArrayOop signers_copy = oopFactory::new_objArray(element, signers->length(), CHECK_NULL);
1081   for (int index = 0; index < signers->length(); index++) {
1082     signers_copy->obj_at_put(index, signers->obj_at(index));
1083   }
1084 
1085   // return the copy
1086   return (jobjectArray) JNIHandles::make_local(env, signers_copy);
1087 JVM_END
1088 
1089 
1090 JVM_ENTRY(void, JVM_SetClassSigners(JNIEnv *env, jclass cls, jobjectArray signers))
1091   JVMWrapper("JVM_SetClassSigners");
1092   if (!java_lang_Class::is_primitive(JNIHandles::resolve_non_null(cls))) {
1093     // This call is ignored for primitive types and arrays.
1094     // Signers are only set once, ClassLoader.java, and thus shouldn't
1095     // be called with an array.  Only the bootstrap loader creates arrays.
1096     Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
1097     if (k->oop_is_instance()) {
1098       java_lang_Class::set_signers(k->java_mirror(), objArrayOop(JNIHandles::resolve(signers)));
1099     }
1100   }
1101 JVM_END
1102 
1103 
1104 JVM_ENTRY(jobject, JVM_GetProtectionDomain(JNIEnv *env, jclass cls))
1105   JVMWrapper("JVM_GetProtectionDomain");
1106   if (JNIHandles::resolve(cls) == NULL) {
1107     THROW_(vmSymbols::java_lang_NullPointerException(), NULL);
1108   }
1109 
1110   if (java_lang_Class::is_primitive(JNIHandles::resolve(cls))) {
1111     // Primitive types does not have a protection domain.
1112     return NULL;
1113   }
1114 
1115   oop pd = java_lang_Class::protection_domain(JNIHandles::resolve(cls));
1116   return (jobject) JNIHandles::make_local(env, pd);
1117 JVM_END
1118 
1119 
1120 static bool is_authorized(Handle context, instanceKlassHandle klass, TRAPS) {
1121   // If there is a security manager and protection domain, check the access
1122   // in the protection domain, otherwise it is authorized.
1123   if (java_lang_System::has_security_manager()) {
1124 
1125     // For bootstrapping, if pd implies method isn't in the JDK, allow
1126     // this context to revert to older behavior.
1127     // In this case the isAuthorized field in AccessControlContext is also not
1128     // present.
1129     if (Universe::protection_domain_implies_method() == NULL) {
1130       return true;
1131     }
1132 
1133     // Whitelist certain access control contexts
1134     if (java_security_AccessControlContext::is_authorized(context)) {
1135       return true;
1136     }
1137 
1138     oop prot = klass->protection_domain();
1139     if (prot != NULL) {
1140       // Call pd.implies(new SecurityPermission("createAccessControlContext"))
1141       // in the new wrapper.
1142       methodHandle m(THREAD, Universe::protection_domain_implies_method());
1143       Handle h_prot(THREAD, prot);
1144       JavaValue result(T_BOOLEAN);
1145       JavaCallArguments args(h_prot);
1146       JavaCalls::call(&result, m, &args, CHECK_false);
1147       return (result.get_jboolean() != 0);
1148     }
1149   }
1150   return true;
1151 }
1152 
1153 // Create an AccessControlContext with a protection domain with null codesource
1154 // and null permissions - which gives no permissions.
1155 oop create_dummy_access_control_context(TRAPS) {
1156   InstanceKlass* pd_klass = InstanceKlass::cast(SystemDictionary::ProtectionDomain_klass());
1157   Handle obj = pd_klass->allocate_instance_handle(CHECK_NULL);
1158   // Call constructor ProtectionDomain(null, null);
1159   JavaValue result(T_VOID);
1160   JavaCalls::call_special(&result, obj, KlassHandle(THREAD, pd_klass),
1161                           vmSymbols::object_initializer_name(),
1162                           vmSymbols::codesource_permissioncollection_signature(),
1163                           Handle(), Handle(), CHECK_NULL);
1164 
1165   // new ProtectionDomain[] {pd};
1166   objArrayOop context = oopFactory::new_objArray(pd_klass, 1, CHECK_NULL);
1167   context->obj_at_put(0, obj());
1168 
1169   // new AccessControlContext(new ProtectionDomain[] {pd})
1170   objArrayHandle h_context(THREAD, context);
1171   oop acc = java_security_AccessControlContext::create(h_context, false, Handle(), CHECK_NULL);
1172   return acc;
1173 }
1174 
1175 JVM_ENTRY(jobject, JVM_DoPrivileged(JNIEnv *env, jclass cls, jobject action, jobject context, jboolean wrapException))
1176   JVMWrapper("JVM_DoPrivileged");
1177 
1178   if (action == NULL) {
1179     THROW_MSG_0(vmSymbols::java_lang_NullPointerException(), "Null action");
1180   }
1181 
1182   // Compute the frame initiating the do privileged operation and setup the privileged stack
1183   vframeStream vfst(thread);
1184   vfst.security_get_caller_frame(1);
1185 
1186   if (vfst.at_end()) {
1187     THROW_MSG_0(vmSymbols::java_lang_InternalError(), "no caller?");
1188   }
1189 
1190   Method* method        = vfst.method();
1191   instanceKlassHandle klass (THREAD, method->method_holder());
1192 
1193   // Check that action object understands "Object run()"
1194   Handle h_context;
1195   if (context != NULL) {
1196     h_context = Handle(THREAD, JNIHandles::resolve(context));
1197     bool authorized = is_authorized(h_context, klass, CHECK_NULL);
1198     if (!authorized) {
1199       // Create an unprivileged access control object and call it's run function
1200       // instead.
1201       oop noprivs = create_dummy_access_control_context(CHECK_NULL);
1202       h_context = Handle(THREAD, noprivs);
1203     }
1204   }
1205 
1206   // Check that action object understands "Object run()"
1207   Handle object (THREAD, JNIHandles::resolve(action));
1208 
1209   // get run() method
1210   Method* m_oop = object->klass()->uncached_lookup_method(
1211                                            vmSymbols::run_method_name(),
1212                                            vmSymbols::void_object_signature(),
1213                                            Klass::normal);
1214   methodHandle m (THREAD, m_oop);
1215   if (m.is_null() || !m->is_method() || !m()->is_public() || m()->is_static()) {
1216     THROW_MSG_0(vmSymbols::java_lang_InternalError(), "No run method");
1217   }
1218 
1219   // Stack allocated list of privileged stack elements
1220   PrivilegedElement pi;
1221   if (!vfst.at_end()) {
1222     pi.initialize(&vfst, h_context(), thread->privileged_stack_top(), CHECK_NULL);
1223     thread->set_privileged_stack_top(&pi);
1224   }
1225 
1226 
1227   // invoke the Object run() in the action object. We cannot use call_interface here, since the static type
1228   // is not really known - it is either java.security.PrivilegedAction or java.security.PrivilegedExceptionAction
1229   Handle pending_exception;
1230   JavaValue result(T_OBJECT);
1231   JavaCallArguments args(object);
1232   JavaCalls::call(&result, m, &args, THREAD);
1233 
1234   // done with action, remove ourselves from the list
1235   if (!vfst.at_end()) {
1236     assert(thread->privileged_stack_top() != NULL && thread->privileged_stack_top() == &pi, "wrong top element");
1237     thread->set_privileged_stack_top(thread->privileged_stack_top()->next());
1238   }
1239 
1240   if (HAS_PENDING_EXCEPTION) {
1241     pending_exception = Handle(THREAD, PENDING_EXCEPTION);
1242     CLEAR_PENDING_EXCEPTION;
1243     // JVMTI has already reported the pending exception
1244     // JVMTI internal flag reset is needed in order to report PrivilegedActionException
1245     if (THREAD->is_Java_thread()) {
1246       JvmtiExport::clear_detected_exception((JavaThread*) THREAD);
1247     }
1248     if ( pending_exception->is_a(SystemDictionary::Exception_klass()) &&
1249         !pending_exception->is_a(SystemDictionary::RuntimeException_klass())) {
1250       // Throw a java.security.PrivilegedActionException(Exception e) exception
1251       JavaCallArguments args(pending_exception);
1252       THROW_ARG_0(vmSymbols::java_security_PrivilegedActionException(),
1253                   vmSymbols::exception_void_signature(),
1254                   &args);
1255     }
1256   }
1257 
1258   if (pending_exception.not_null()) THROW_OOP_0(pending_exception());
1259   return JNIHandles::make_local(env, (oop) result.get_jobject());
1260 JVM_END
1261 
1262 
1263 // Returns the inherited_access_control_context field of the running thread.
1264 JVM_ENTRY(jobject, JVM_GetInheritedAccessControlContext(JNIEnv *env, jclass cls))
1265   JVMWrapper("JVM_GetInheritedAccessControlContext");
1266   oop result = java_lang_Thread::inherited_access_control_context(thread->threadObj());
1267   return JNIHandles::make_local(env, result);
1268 JVM_END
1269 
1270 class RegisterArrayForGC {
1271  private:
1272   JavaThread *_thread;
1273  public:
1274   RegisterArrayForGC(JavaThread *thread, GrowableArray<oop>* array)  {
1275     _thread = thread;
1276     _thread->register_array_for_gc(array);
1277   }
1278 
1279   ~RegisterArrayForGC() {
1280     _thread->register_array_for_gc(NULL);
1281   }
1282 };
1283 
1284 
1285 JVM_ENTRY(jobject, JVM_GetStackAccessControlContext(JNIEnv *env, jclass cls))
1286   JVMWrapper("JVM_GetStackAccessControlContext");
1287   if (!UsePrivilegedStack) return NULL;
1288 
1289   ResourceMark rm(THREAD);
1290   GrowableArray<oop>* local_array = new GrowableArray<oop>(12);
1291   JvmtiVMObjectAllocEventCollector oam;
1292 
1293   // count the protection domains on the execution stack. We collapse
1294   // duplicate consecutive protection domains into a single one, as
1295   // well as stopping when we hit a privileged frame.
1296 
1297   // Use vframeStream to iterate through Java frames
1298   vframeStream vfst(thread);
1299 
1300   oop previous_protection_domain = NULL;
1301   Handle privileged_context(thread, NULL);
1302   bool is_privileged = false;
1303   oop protection_domain = NULL;
1304 
1305   for(; !vfst.at_end(); vfst.next()) {
1306     // get method of frame
1307     Method* method = vfst.method();
1308     intptr_t* frame_id   = vfst.frame_id();
1309 
1310     // check the privileged frames to see if we have a match
1311     if (thread->privileged_stack_top() && thread->privileged_stack_top()->frame_id() == frame_id) {
1312       // this frame is privileged
1313       is_privileged = true;
1314       privileged_context = Handle(thread, thread->privileged_stack_top()->privileged_context());
1315       protection_domain  = thread->privileged_stack_top()->protection_domain();
1316     } else {
1317       protection_domain = method->method_holder()->protection_domain();
1318     }
1319 
1320     if ((previous_protection_domain != protection_domain) && (protection_domain != NULL)) {
1321       local_array->push(protection_domain);
1322       previous_protection_domain = protection_domain;
1323     }
1324 
1325     if (is_privileged) break;
1326   }
1327 
1328 
1329   // either all the domains on the stack were system domains, or
1330   // we had a privileged system domain
1331   if (local_array->is_empty()) {
1332     if (is_privileged && privileged_context.is_null()) return NULL;
1333 
1334     oop result = java_security_AccessControlContext::create(objArrayHandle(), is_privileged, privileged_context, CHECK_NULL);
1335     return JNIHandles::make_local(env, result);
1336   }
1337 
1338   // the resource area must be registered in case of a gc
1339   RegisterArrayForGC ragc(thread, local_array);
1340   objArrayOop context = oopFactory::new_objArray(SystemDictionary::ProtectionDomain_klass(),
1341                                                  local_array->length(), CHECK_NULL);
1342   objArrayHandle h_context(thread, context);
1343   for (int index = 0; index < local_array->length(); index++) {
1344     h_context->obj_at_put(index, local_array->at(index));
1345   }
1346 
1347   oop result = java_security_AccessControlContext::create(h_context, is_privileged, privileged_context, CHECK_NULL);
1348 
1349   return JNIHandles::make_local(env, result);
1350 JVM_END
1351 
1352 
1353 JVM_QUICK_ENTRY(jboolean, JVM_IsArrayClass(JNIEnv *env, jclass cls))
1354   JVMWrapper("JVM_IsArrayClass");
1355   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
1356   return (k != NULL) && k->oop_is_array() ? true : false;
1357 JVM_END
1358 
1359 
1360 JVM_QUICK_ENTRY(jboolean, JVM_IsPrimitiveClass(JNIEnv *env, jclass cls))
1361   JVMWrapper("JVM_IsPrimitiveClass");
1362   oop mirror = JNIHandles::resolve_non_null(cls);
1363   return (jboolean) java_lang_Class::is_primitive(mirror);
1364 JVM_END
1365 
1366 
1367 JVM_ENTRY(jint, JVM_GetClassModifiers(JNIEnv *env, jclass cls))
1368   JVMWrapper("JVM_GetClassModifiers");
1369   if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(cls))) {
1370     // Primitive type
1371     return JVM_ACC_ABSTRACT | JVM_ACC_FINAL | JVM_ACC_PUBLIC;
1372   }
1373 
1374   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
1375   debug_only(int computed_modifiers = k->compute_modifier_flags(CHECK_0));
1376   assert(k->modifier_flags() == computed_modifiers, "modifiers cache is OK");
1377   return k->modifier_flags();
1378 JVM_END
1379 
1380 
1381 // Inner class reflection ///////////////////////////////////////////////////////////////////////////////
1382 
1383 JVM_ENTRY(jobjectArray, JVM_GetDeclaredClasses(JNIEnv *env, jclass ofClass))
1384   JvmtiVMObjectAllocEventCollector oam;
1385   // ofClass is a reference to a java_lang_Class object. The mirror object
1386   // of an InstanceKlass
1387 
1388   if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(ofClass)) ||
1389       ! java_lang_Class::as_Klass(JNIHandles::resolve_non_null(ofClass))->oop_is_instance()) {
1390     oop result = oopFactory::new_objArray(SystemDictionary::Class_klass(), 0, CHECK_NULL);
1391     return (jobjectArray)JNIHandles::make_local(env, result);
1392   }
1393 
1394   instanceKlassHandle k(thread, java_lang_Class::as_Klass(JNIHandles::resolve_non_null(ofClass)));
1395   InnerClassesIterator iter(k);
1396 
1397   if (iter.length() == 0) {
1398     // Neither an inner nor outer class
1399     oop result = oopFactory::new_objArray(SystemDictionary::Class_klass(), 0, CHECK_NULL);
1400     return (jobjectArray)JNIHandles::make_local(env, result);
1401   }
1402 
1403   // find inner class info
1404   constantPoolHandle cp(thread, k->constants());
1405   int length = iter.length();
1406 
1407   // Allocate temp. result array
1408   objArrayOop r = oopFactory::new_objArray(SystemDictionary::Class_klass(), length/4, CHECK_NULL);
1409   objArrayHandle result (THREAD, r);
1410   int members = 0;
1411 
1412   for (; !iter.done(); iter.next()) {
1413     int ioff = iter.inner_class_info_index();
1414     int ooff = iter.outer_class_info_index();
1415 
1416     if (ioff != 0 && ooff != 0) {
1417       // Check to see if the name matches the class we're looking for
1418       // before attempting to find the class.
1419       if (cp->klass_name_at_matches(k, ooff)) {
1420         Klass* outer_klass = cp->klass_at(ooff, CHECK_NULL);
1421         if (outer_klass == k()) {
1422            Klass* ik = cp->klass_at(ioff, CHECK_NULL);
1423            instanceKlassHandle inner_klass (THREAD, ik);
1424 
1425            // Throws an exception if outer klass has not declared k as
1426            // an inner klass
1427            Reflection::check_for_inner_class(k, inner_klass, true, CHECK_NULL);
1428 
1429            result->obj_at_put(members, inner_klass->java_mirror());
1430            members++;
1431         }
1432       }
1433     }
1434   }
1435 
1436   if (members != length) {
1437     // Return array of right length
1438     objArrayOop res = oopFactory::new_objArray(SystemDictionary::Class_klass(), members, CHECK_NULL);
1439     for(int i = 0; i < members; i++) {
1440       res->obj_at_put(i, result->obj_at(i));
1441     }
1442     return (jobjectArray)JNIHandles::make_local(env, res);
1443   }
1444 
1445   return (jobjectArray)JNIHandles::make_local(env, result());
1446 JVM_END
1447 
1448 
1449 JVM_ENTRY(jclass, JVM_GetDeclaringClass(JNIEnv *env, jclass ofClass))
1450 {
1451   // ofClass is a reference to a java_lang_Class object.
1452   if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(ofClass)) ||
1453       ! java_lang_Class::as_Klass(JNIHandles::resolve_non_null(ofClass))->oop_is_instance()) {
1454     return NULL;
1455   }
1456 
1457   bool inner_is_member = false;
1458   Klass* outer_klass
1459     = InstanceKlass::cast(java_lang_Class::as_Klass(JNIHandles::resolve_non_null(ofClass))
1460                           )->compute_enclosing_class(&inner_is_member, CHECK_NULL);
1461   if (outer_klass == NULL)  return NULL;  // already a top-level class
1462   if (!inner_is_member)  return NULL;     // an anonymous class (inside a method)
1463   return (jclass) JNIHandles::make_local(env, outer_klass->java_mirror());
1464 }
1465 JVM_END
1466 
1467 // should be in InstanceKlass.cpp, but is here for historical reasons
1468 Klass* InstanceKlass::compute_enclosing_class_impl(instanceKlassHandle k,
1469                                                      bool* inner_is_member,
1470                                                      TRAPS) {
1471   Thread* thread = THREAD;
1472   InnerClassesIterator iter(k);
1473   if (iter.length() == 0) {
1474     // No inner class info => no declaring class
1475     return NULL;
1476   }
1477 
1478   constantPoolHandle i_cp(thread, k->constants());
1479 
1480   bool found = false;
1481   Klass* ok;
1482   instanceKlassHandle outer_klass;
1483   *inner_is_member = false;
1484 
1485   // Find inner_klass attribute
1486   for (; !iter.done() && !found; iter.next()) {
1487     int ioff = iter.inner_class_info_index();
1488     int ooff = iter.outer_class_info_index();
1489     int noff = iter.inner_name_index();
1490     if (ioff != 0) {
1491       // Check to see if the name matches the class we're looking for
1492       // before attempting to find the class.
1493       if (i_cp->klass_name_at_matches(k, ioff)) {
1494         Klass* inner_klass = i_cp->klass_at(ioff, CHECK_NULL);
1495         found = (k() == inner_klass);
1496         if (found && ooff != 0) {
1497           ok = i_cp->klass_at(ooff, CHECK_NULL);
1498           outer_klass = instanceKlassHandle(thread, ok);
1499           *inner_is_member = true;
1500         }
1501       }
1502     }
1503   }
1504 
1505   if (found && outer_klass.is_null()) {
1506     // It may be anonymous; try for that.
1507     int encl_method_class_idx = k->enclosing_method_class_index();
1508     if (encl_method_class_idx != 0) {
1509       ok = i_cp->klass_at(encl_method_class_idx, CHECK_NULL);
1510       outer_klass = instanceKlassHandle(thread, ok);
1511       *inner_is_member = false;
1512     }
1513   }
1514 
1515   // If no inner class attribute found for this class.
1516   if (outer_klass.is_null())  return NULL;
1517 
1518   // Throws an exception if outer klass has not declared k as an inner klass
1519   // We need evidence that each klass knows about the other, or else
1520   // the system could allow a spoof of an inner class to gain access rights.
1521   Reflection::check_for_inner_class(outer_klass, k, *inner_is_member, CHECK_NULL);
1522   return outer_klass();
1523 }
1524 
1525 JVM_ENTRY(jstring, JVM_GetClassSignature(JNIEnv *env, jclass cls))
1526   assert (cls != NULL, "illegal class");
1527   JVMWrapper("JVM_GetClassSignature");
1528   JvmtiVMObjectAllocEventCollector oam;
1529   ResourceMark rm(THREAD);
1530   // Return null for arrays and primatives
1531   if (!java_lang_Class::is_primitive(JNIHandles::resolve(cls))) {
1532     Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve(cls));
1533     if (k->oop_is_instance()) {
1534       Symbol* sym = InstanceKlass::cast(k)->generic_signature();
1535       if (sym == NULL) return NULL;
1536       Handle str = java_lang_String::create_from_symbol(sym, CHECK_NULL);
1537       return (jstring) JNIHandles::make_local(env, str());
1538     }
1539   }
1540   return NULL;
1541 JVM_END
1542 
1543 
1544 JVM_ENTRY(jbyteArray, JVM_GetClassAnnotations(JNIEnv *env, jclass cls))
1545   assert (cls != NULL, "illegal class");
1546   JVMWrapper("JVM_GetClassAnnotations");
1547 
1548   // Return null for arrays and primitives
1549   if (!java_lang_Class::is_primitive(JNIHandles::resolve(cls))) {
1550     Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve(cls));
1551     if (k->oop_is_instance()) {
1552       typeArrayOop a = Annotations::make_java_array(InstanceKlass::cast(k)->class_annotations(), CHECK_NULL);
1553       return (jbyteArray) JNIHandles::make_local(env, a);
1554     }
1555   }
1556   return NULL;
1557 JVM_END
1558 
1559 
1560 static bool jvm_get_field_common(jobject field, fieldDescriptor& fd, TRAPS) {
1561   // some of this code was adapted from from jni_FromReflectedField
1562 
1563   oop reflected = JNIHandles::resolve_non_null(field);
1564   oop mirror    = java_lang_reflect_Field::clazz(reflected);
1565   Klass* k    = java_lang_Class::as_Klass(mirror);
1566   int slot      = java_lang_reflect_Field::slot(reflected);
1567   int modifiers = java_lang_reflect_Field::modifiers(reflected);
1568 
1569   KlassHandle kh(THREAD, k);
1570   intptr_t offset = InstanceKlass::cast(kh())->field_offset(slot);
1571 
1572   if (modifiers & JVM_ACC_STATIC) {
1573     // for static fields we only look in the current class
1574     if (!InstanceKlass::cast(kh())->find_local_field_from_offset(offset, true, &fd)) {
1575       assert(false, "cannot find static field");
1576       return false;
1577     }
1578   } else {
1579     // for instance fields we start with the current class and work
1580     // our way up through the superclass chain
1581     if (!InstanceKlass::cast(kh())->find_field_from_offset(offset, false, &fd)) {
1582       assert(false, "cannot find instance field");
1583       return false;
1584     }
1585   }
1586   return true;
1587 }
1588 
1589 static Method* jvm_get_method_common(jobject method) {
1590   // some of this code was adapted from from jni_FromReflectedMethod
1591 
1592   oop reflected = JNIHandles::resolve_non_null(method);
1593   oop mirror    = NULL;
1594   int slot      = 0;
1595 
1596   if (reflected->klass() == SystemDictionary::reflect_Constructor_klass()) {
1597     mirror = java_lang_reflect_Constructor::clazz(reflected);
1598     slot   = java_lang_reflect_Constructor::slot(reflected);
1599   } else {
1600     assert(reflected->klass() == SystemDictionary::reflect_Method_klass(),
1601            "wrong type");
1602     mirror = java_lang_reflect_Method::clazz(reflected);
1603     slot   = java_lang_reflect_Method::slot(reflected);
1604   }
1605   Klass* k = java_lang_Class::as_Klass(mirror);
1606 
1607   Method* m = InstanceKlass::cast(k)->method_with_idnum(slot);
1608   assert(m != NULL, "cannot find method");
1609   return m;  // caller has to deal with NULL in product mode
1610 }
1611 
1612 /* Type use annotations support (JDK 1.8) */
1613 
1614 JVM_ENTRY(jbyteArray, JVM_GetClassTypeAnnotations(JNIEnv *env, jclass cls))
1615   assert (cls != NULL, "illegal class");
1616   JVMWrapper("JVM_GetClassTypeAnnotations");
1617   ResourceMark rm(THREAD);
1618   // Return null for arrays and primitives
1619   if (!java_lang_Class::is_primitive(JNIHandles::resolve(cls))) {
1620     Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve(cls));
1621     if (k->oop_is_instance()) {
1622       AnnotationArray* type_annotations = InstanceKlass::cast(k)->class_type_annotations();
1623       if (type_annotations != NULL) {
1624         typeArrayOop a = Annotations::make_java_array(type_annotations, CHECK_NULL);
1625         return (jbyteArray) JNIHandles::make_local(env, a);
1626       }
1627     }
1628   }
1629   return NULL;
1630 JVM_END
1631 
1632 JVM_ENTRY(jbyteArray, JVM_GetMethodTypeAnnotations(JNIEnv *env, jobject method))
1633   assert (method != NULL, "illegal method");
1634   JVMWrapper("JVM_GetMethodTypeAnnotations");
1635 
1636   // method is a handle to a java.lang.reflect.Method object
1637   Method* m = jvm_get_method_common(method);
1638   if (m == NULL) {
1639     return NULL;
1640   }
1641 
1642   AnnotationArray* type_annotations = m->type_annotations();
1643   if (type_annotations != NULL) {
1644     typeArrayOop a = Annotations::make_java_array(type_annotations, CHECK_NULL);
1645     return (jbyteArray) JNIHandles::make_local(env, a);
1646   }
1647 
1648   return NULL;
1649 JVM_END
1650 
1651 JVM_ENTRY(jbyteArray, JVM_GetFieldTypeAnnotations(JNIEnv *env, jobject field))
1652   assert (field != NULL, "illegal field");
1653   JVMWrapper("JVM_GetFieldTypeAnnotations");
1654 
1655   fieldDescriptor fd;
1656   bool gotFd = jvm_get_field_common(field, fd, CHECK_NULL);
1657   if (!gotFd) {
1658     return NULL;
1659   }
1660 
1661   return (jbyteArray) JNIHandles::make_local(env, Annotations::make_java_array(fd.type_annotations(), THREAD));
1662 JVM_END
1663 
1664 static void bounds_check(constantPoolHandle cp, jint index, TRAPS) {
1665   if (!cp->is_within_bounds(index)) {
1666     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "Constant pool index out of bounds");
1667   }
1668 }
1669 
1670 JVM_ENTRY(jobjectArray, JVM_GetMethodParameters(JNIEnv *env, jobject method))
1671 {
1672   JVMWrapper("JVM_GetMethodParameters");
1673   // method is a handle to a java.lang.reflect.Method object
1674   Method* method_ptr = jvm_get_method_common(method);
1675   methodHandle mh (THREAD, method_ptr);
1676   Handle reflected_method (THREAD, JNIHandles::resolve_non_null(method));
1677   const int num_params = mh->method_parameters_length();
1678 
1679   if (num_params < 0) {
1680     // A -1 return value from method_parameters_length means there is no
1681     // parameter data.  Return null to indicate this to the reflection
1682     // API.
1683     assert(num_params == -1, "num_params should be -1 if it is less than zero");
1684     return (jobjectArray)NULL;
1685   } else {
1686     // Otherwise, we return something up to reflection, even if it is
1687     // a zero-length array.  Why?  Because in some cases this can
1688     // trigger a MalformedParametersException.
1689 
1690     // make sure all the symbols are properly formatted
1691     for (int i = 0; i < num_params; i++) {
1692       MethodParametersElement* params = mh->method_parameters_start();
1693       int index = params[i].name_cp_index;
1694       bounds_check(mh->constants(), index, CHECK_NULL);
1695 
1696       if (0 != index && !mh->constants()->tag_at(index).is_utf8()) {
1697         THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
1698                     "Wrong type at constant pool index");
1699       }
1700 
1701     }
1702 
1703     objArrayOop result_oop = oopFactory::new_objArray(SystemDictionary::reflect_Parameter_klass(), num_params, CHECK_NULL);
1704     objArrayHandle result (THREAD, result_oop);
1705 
1706     for (int i = 0; i < num_params; i++) {
1707       MethodParametersElement* params = mh->method_parameters_start();
1708       // For a 0 index, give a NULL symbol
1709       Symbol* sym = 0 != params[i].name_cp_index ?
1710         mh->constants()->symbol_at(params[i].name_cp_index) : NULL;
1711       int flags = params[i].flags;
1712       oop param = Reflection::new_parameter(reflected_method, i, sym,
1713                                             flags, CHECK_NULL);
1714       result->obj_at_put(i, param);
1715     }
1716     return (jobjectArray)JNIHandles::make_local(env, result());
1717   }
1718 }
1719 JVM_END
1720 
1721 // New (JDK 1.4) reflection implementation /////////////////////////////////////
1722 
1723 JVM_ENTRY(jobjectArray, JVM_GetClassDeclaredFields(JNIEnv *env, jclass ofClass, jboolean publicOnly))
1724 {
1725   JVMWrapper("JVM_GetClassDeclaredFields");
1726   JvmtiVMObjectAllocEventCollector oam;
1727 
1728   // Exclude primitive types and array types
1729   if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(ofClass)) ||
1730       java_lang_Class::as_Klass(JNIHandles::resolve_non_null(ofClass))->oop_is_array()) {
1731     // Return empty array
1732     oop res = oopFactory::new_objArray(SystemDictionary::reflect_Field_klass(), 0, CHECK_NULL);
1733     return (jobjectArray) JNIHandles::make_local(env, res);
1734   }
1735 
1736   instanceKlassHandle k(THREAD, java_lang_Class::as_Klass(JNIHandles::resolve_non_null(ofClass)));
1737   constantPoolHandle cp(THREAD, k->constants());
1738 
1739   // Ensure class is linked
1740   k->link_class(CHECK_NULL);
1741 
1742   // 4496456 We need to filter out java.lang.Throwable.backtrace
1743   bool skip_backtrace = false;
1744 
1745   // Allocate result
1746   int num_fields;
1747 
1748   if (publicOnly) {
1749     num_fields = 0;
1750     for (JavaFieldStream fs(k()); !fs.done(); fs.next()) {
1751       if (fs.access_flags().is_public()) ++num_fields;
1752     }
1753   } else {
1754     num_fields = k->java_fields_count();
1755 
1756     if (k() == SystemDictionary::Throwable_klass()) {
1757       num_fields--;
1758       skip_backtrace = true;
1759     }
1760   }
1761 
1762   objArrayOop r = oopFactory::new_objArray(SystemDictionary::reflect_Field_klass(), num_fields, CHECK_NULL);
1763   objArrayHandle result (THREAD, r);
1764 
1765   int out_idx = 0;
1766   fieldDescriptor fd;
1767   for (JavaFieldStream fs(k); !fs.done(); fs.next()) {
1768     if (skip_backtrace) {
1769       // 4496456 skip java.lang.Throwable.backtrace
1770       int offset = fs.offset();
1771       if (offset == java_lang_Throwable::get_backtrace_offset()) continue;
1772     }
1773 
1774     if (!publicOnly || fs.access_flags().is_public()) {
1775       fd.reinitialize(k(), fs.index());
1776       oop field = Reflection::new_field(&fd, CHECK_NULL);
1777       result->obj_at_put(out_idx, field);
1778       ++out_idx;
1779     }
1780   }
1781   assert(out_idx == num_fields, "just checking");
1782   return (jobjectArray) JNIHandles::make_local(env, result());
1783 }
1784 JVM_END
1785 
1786 static bool select_method(methodHandle method, bool want_constructor) {
1787   if (want_constructor) {
1788     return (method->is_initializer() && !method->is_static());
1789   } else {
1790     return  (!method->is_initializer() && !method->is_overpass());
1791   }
1792 }
1793 
1794 static jobjectArray get_class_declared_methods_helper(
1795                                   JNIEnv *env,
1796                                   jclass ofClass, jboolean publicOnly,
1797                                   bool want_constructor,
1798                                   Klass* klass, TRAPS) {
1799 
1800   JvmtiVMObjectAllocEventCollector oam;
1801 
1802   // Exclude primitive types and array types
1803   if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(ofClass))
1804       || java_lang_Class::as_Klass(JNIHandles::resolve_non_null(ofClass))->oop_is_array()) {
1805     // Return empty array
1806     oop res = oopFactory::new_objArray(klass, 0, CHECK_NULL);
1807     return (jobjectArray) JNIHandles::make_local(env, res);
1808   }
1809 
1810   instanceKlassHandle k(THREAD, java_lang_Class::as_Klass(JNIHandles::resolve_non_null(ofClass)));
1811 
1812   // Ensure class is linked
1813   k->link_class(CHECK_NULL);
1814 
1815   Array<Method*>* methods = k->methods();
1816   int methods_length = methods->length();
1817 
1818   // Save original method_idnum in case of redefinition, which can change
1819   // the idnum of obsolete methods.  The new method will have the same idnum
1820   // but if we refresh the methods array, the counts will be wrong.
1821   ResourceMark rm(THREAD);
1822   GrowableArray<int>* idnums = new GrowableArray<int>(methods_length);
1823   int num_methods = 0;
1824 
1825   for (int i = 0; i < methods_length; i++) {
1826     methodHandle method(THREAD, methods->at(i));
1827     if (select_method(method, want_constructor)) {
1828       if (!publicOnly || method->is_public()) {
1829         idnums->push(method->method_idnum());
1830         ++num_methods;
1831       }
1832     }
1833   }
1834 
1835   // Allocate result
1836   objArrayOop r = oopFactory::new_objArray(klass, num_methods, CHECK_NULL);
1837   objArrayHandle result (THREAD, r);
1838 
1839   // Now just put the methods that we selected above, but go by their idnum
1840   // in case of redefinition.  The methods can be redefined at any safepoint,
1841   // so above when allocating the oop array and below when creating reflect
1842   // objects.
1843   for (int i = 0; i < num_methods; i++) {
1844     methodHandle method(THREAD, k->method_with_idnum(idnums->at(i)));
1845     if (method.is_null()) {
1846       // Method may have been deleted and seems this API can handle null
1847       // Otherwise should probably put a method that throws NSME
1848       result->obj_at_put(i, NULL);
1849     } else {
1850       oop m;
1851       if (want_constructor) {
1852         m = Reflection::new_constructor(method, CHECK_NULL);
1853       } else {
1854         m = Reflection::new_method(method, false, CHECK_NULL);
1855       }
1856       result->obj_at_put(i, m);
1857     }
1858   }
1859 
1860   return (jobjectArray) JNIHandles::make_local(env, result());
1861 }
1862 
1863 JVM_ENTRY(jobjectArray, JVM_GetClassDeclaredMethods(JNIEnv *env, jclass ofClass, jboolean publicOnly))
1864 {
1865   JVMWrapper("JVM_GetClassDeclaredMethods");
1866   return get_class_declared_methods_helper(env, ofClass, publicOnly,
1867                                            /*want_constructor*/ false,
1868                                            SystemDictionary::reflect_Method_klass(), THREAD);
1869 }
1870 JVM_END
1871 
1872 JVM_ENTRY(jobjectArray, JVM_GetClassDeclaredConstructors(JNIEnv *env, jclass ofClass, jboolean publicOnly))
1873 {
1874   JVMWrapper("JVM_GetClassDeclaredConstructors");
1875   return get_class_declared_methods_helper(env, ofClass, publicOnly,
1876                                            /*want_constructor*/ true,
1877                                            SystemDictionary::reflect_Constructor_klass(), THREAD);
1878 }
1879 JVM_END
1880 
1881 JVM_ENTRY(jint, JVM_GetClassAccessFlags(JNIEnv *env, jclass cls))
1882 {
1883   JVMWrapper("JVM_GetClassAccessFlags");
1884   if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(cls))) {
1885     // Primitive type
1886     return JVM_ACC_ABSTRACT | JVM_ACC_FINAL | JVM_ACC_PUBLIC;
1887   }
1888 
1889   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
1890   return k->access_flags().as_int() & JVM_ACC_WRITTEN_FLAGS;
1891 }
1892 JVM_END
1893 
1894 
1895 // Constant pool access //////////////////////////////////////////////////////////
1896 
1897 JVM_ENTRY(jobject, JVM_GetClassConstantPool(JNIEnv *env, jclass cls))
1898 {
1899   JVMWrapper("JVM_GetClassConstantPool");
1900   JvmtiVMObjectAllocEventCollector oam;
1901 
1902   // Return null for primitives and arrays
1903   if (!java_lang_Class::is_primitive(JNIHandles::resolve_non_null(cls))) {
1904     Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
1905     if (k->oop_is_instance()) {
1906       instanceKlassHandle k_h(THREAD, k);
1907       Handle jcp = sun_reflect_ConstantPool::create(CHECK_NULL);
1908       sun_reflect_ConstantPool::set_cp(jcp(), k_h->constants());
1909       return JNIHandles::make_local(jcp());
1910     }
1911   }
1912   return NULL;
1913 }
1914 JVM_END
1915 
1916 
1917 JVM_ENTRY(jint, JVM_ConstantPoolGetSize(JNIEnv *env, jobject obj, jobject unused))
1918 {
1919   JVMWrapper("JVM_ConstantPoolGetSize");
1920   constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
1921   return cp->length();
1922 }
1923 JVM_END
1924 
1925 
1926 JVM_ENTRY(jclass, JVM_ConstantPoolGetClassAt(JNIEnv *env, jobject obj, jobject unused, jint index))
1927 {
1928   JVMWrapper("JVM_ConstantPoolGetClassAt");
1929   constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
1930   bounds_check(cp, index, CHECK_NULL);
1931   constantTag tag = cp->tag_at(index);
1932   if (!tag.is_klass() && !tag.is_unresolved_klass()) {
1933     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
1934   }
1935   Klass* k = cp->klass_at(index, CHECK_NULL);
1936   return (jclass) JNIHandles::make_local(k->java_mirror());
1937 }
1938 JVM_END
1939 
1940 JVM_ENTRY(jclass, JVM_ConstantPoolGetClassAtIfLoaded(JNIEnv *env, jobject obj, jobject unused, jint index))
1941 {
1942   JVMWrapper("JVM_ConstantPoolGetClassAtIfLoaded");
1943   constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
1944   bounds_check(cp, index, CHECK_NULL);
1945   constantTag tag = cp->tag_at(index);
1946   if (!tag.is_klass() && !tag.is_unresolved_klass()) {
1947     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
1948   }
1949   Klass* k = ConstantPool::klass_at_if_loaded(cp, index);
1950   if (k == NULL) return NULL;
1951   return (jclass) JNIHandles::make_local(k->java_mirror());
1952 }
1953 JVM_END
1954 
1955 static jobject get_method_at_helper(constantPoolHandle cp, jint index, bool force_resolution, TRAPS) {
1956   constantTag tag = cp->tag_at(index);
1957   if (!tag.is_method() && !tag.is_interface_method()) {
1958     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
1959   }
1960   int klass_ref  = cp->uncached_klass_ref_index_at(index);
1961   Klass* k_o;
1962   if (force_resolution) {
1963     k_o = cp->klass_at(klass_ref, CHECK_NULL);
1964   } else {
1965     k_o = ConstantPool::klass_at_if_loaded(cp, klass_ref);
1966     if (k_o == NULL) return NULL;
1967   }
1968   instanceKlassHandle k(THREAD, k_o);
1969   Symbol* name = cp->uncached_name_ref_at(index);
1970   Symbol* sig  = cp->uncached_signature_ref_at(index);
1971   methodHandle m (THREAD, k->find_method(name, sig));
1972   if (m.is_null()) {
1973     THROW_MSG_0(vmSymbols::java_lang_RuntimeException(), "Unable to look up method in target class");
1974   }
1975   oop method;
1976   if (!m->is_initializer() || m->is_static()) {
1977     method = Reflection::new_method(m, true, CHECK_NULL);
1978   } else {
1979     method = Reflection::new_constructor(m, CHECK_NULL);
1980   }
1981   return JNIHandles::make_local(method);
1982 }
1983 
1984 JVM_ENTRY(jobject, JVM_ConstantPoolGetMethodAt(JNIEnv *env, jobject obj, jobject unused, jint index))
1985 {
1986   JVMWrapper("JVM_ConstantPoolGetMethodAt");
1987   JvmtiVMObjectAllocEventCollector oam;
1988   constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
1989   bounds_check(cp, index, CHECK_NULL);
1990   jobject res = get_method_at_helper(cp, index, true, CHECK_NULL);
1991   return res;
1992 }
1993 JVM_END
1994 
1995 JVM_ENTRY(jobject, JVM_ConstantPoolGetMethodAtIfLoaded(JNIEnv *env, jobject obj, jobject unused, jint index))
1996 {
1997   JVMWrapper("JVM_ConstantPoolGetMethodAtIfLoaded");
1998   JvmtiVMObjectAllocEventCollector oam;
1999   constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2000   bounds_check(cp, index, CHECK_NULL);
2001   jobject res = get_method_at_helper(cp, index, false, CHECK_NULL);
2002   return res;
2003 }
2004 JVM_END
2005 
2006 static jobject get_field_at_helper(constantPoolHandle cp, jint index, bool force_resolution, TRAPS) {
2007   constantTag tag = cp->tag_at(index);
2008   if (!tag.is_field()) {
2009     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2010   }
2011   int klass_ref  = cp->uncached_klass_ref_index_at(index);
2012   Klass* k_o;
2013   if (force_resolution) {
2014     k_o = cp->klass_at(klass_ref, CHECK_NULL);
2015   } else {
2016     k_o = ConstantPool::klass_at_if_loaded(cp, klass_ref);
2017     if (k_o == NULL) return NULL;
2018   }
2019   instanceKlassHandle k(THREAD, k_o);
2020   Symbol* name = cp->uncached_name_ref_at(index);
2021   Symbol* sig  = cp->uncached_signature_ref_at(index);
2022   fieldDescriptor fd;
2023   Klass* target_klass = k->find_field(name, sig, &fd);
2024   if (target_klass == NULL) {
2025     THROW_MSG_0(vmSymbols::java_lang_RuntimeException(), "Unable to look up field in target class");
2026   }
2027   oop field = Reflection::new_field(&fd, CHECK_NULL);
2028   return JNIHandles::make_local(field);
2029 }
2030 
2031 JVM_ENTRY(jobject, JVM_ConstantPoolGetFieldAt(JNIEnv *env, jobject obj, jobject unusedl, jint index))
2032 {
2033   JVMWrapper("JVM_ConstantPoolGetFieldAt");
2034   JvmtiVMObjectAllocEventCollector oam;
2035   constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2036   bounds_check(cp, index, CHECK_NULL);
2037   jobject res = get_field_at_helper(cp, index, true, CHECK_NULL);
2038   return res;
2039 }
2040 JVM_END
2041 
2042 JVM_ENTRY(jobject, JVM_ConstantPoolGetFieldAtIfLoaded(JNIEnv *env, jobject obj, jobject unused, jint index))
2043 {
2044   JVMWrapper("JVM_ConstantPoolGetFieldAtIfLoaded");
2045   JvmtiVMObjectAllocEventCollector oam;
2046   constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2047   bounds_check(cp, index, CHECK_NULL);
2048   jobject res = get_field_at_helper(cp, index, false, CHECK_NULL);
2049   return res;
2050 }
2051 JVM_END
2052 
2053 JVM_ENTRY(jobjectArray, JVM_ConstantPoolGetMemberRefInfoAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2054 {
2055   JVMWrapper("JVM_ConstantPoolGetMemberRefInfoAt");
2056   JvmtiVMObjectAllocEventCollector oam;
2057   constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2058   bounds_check(cp, index, CHECK_NULL);
2059   constantTag tag = cp->tag_at(index);
2060   if (!tag.is_field_or_method()) {
2061     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2062   }
2063   int klass_ref = cp->uncached_klass_ref_index_at(index);
2064   Symbol*  klass_name  = cp->klass_name_at(klass_ref);
2065   Symbol*  member_name = cp->uncached_name_ref_at(index);
2066   Symbol*  member_sig  = cp->uncached_signature_ref_at(index);
2067   objArrayOop  dest_o = oopFactory::new_objArray(SystemDictionary::String_klass(), 3, CHECK_NULL);
2068   objArrayHandle dest(THREAD, dest_o);
2069   Handle str = java_lang_String::create_from_symbol(klass_name, CHECK_NULL);
2070   dest->obj_at_put(0, str());
2071   str = java_lang_String::create_from_symbol(member_name, CHECK_NULL);
2072   dest->obj_at_put(1, str());
2073   str = java_lang_String::create_from_symbol(member_sig, CHECK_NULL);
2074   dest->obj_at_put(2, str());
2075   return (jobjectArray) JNIHandles::make_local(dest());
2076 }
2077 JVM_END
2078 
2079 JVM_ENTRY(jint, JVM_ConstantPoolGetIntAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2080 {
2081   JVMWrapper("JVM_ConstantPoolGetIntAt");
2082   constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2083   bounds_check(cp, index, CHECK_0);
2084   constantTag tag = cp->tag_at(index);
2085   if (!tag.is_int()) {
2086     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2087   }
2088   return cp->int_at(index);
2089 }
2090 JVM_END
2091 
2092 JVM_ENTRY(jlong, JVM_ConstantPoolGetLongAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2093 {
2094   JVMWrapper("JVM_ConstantPoolGetLongAt");
2095   constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2096   bounds_check(cp, index, CHECK_(0L));
2097   constantTag tag = cp->tag_at(index);
2098   if (!tag.is_long()) {
2099     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2100   }
2101   return cp->long_at(index);
2102 }
2103 JVM_END
2104 
2105 JVM_ENTRY(jfloat, JVM_ConstantPoolGetFloatAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2106 {
2107   JVMWrapper("JVM_ConstantPoolGetFloatAt");
2108   constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2109   bounds_check(cp, index, CHECK_(0.0f));
2110   constantTag tag = cp->tag_at(index);
2111   if (!tag.is_float()) {
2112     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2113   }
2114   return cp->float_at(index);
2115 }
2116 JVM_END
2117 
2118 JVM_ENTRY(jdouble, JVM_ConstantPoolGetDoubleAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2119 {
2120   JVMWrapper("JVM_ConstantPoolGetDoubleAt");
2121   constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2122   bounds_check(cp, index, CHECK_(0.0));
2123   constantTag tag = cp->tag_at(index);
2124   if (!tag.is_double()) {
2125     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2126   }
2127   return cp->double_at(index);
2128 }
2129 JVM_END
2130 
2131 JVM_ENTRY(jstring, JVM_ConstantPoolGetStringAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2132 {
2133   JVMWrapper("JVM_ConstantPoolGetStringAt");
2134   constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2135   bounds_check(cp, index, CHECK_NULL);
2136   constantTag tag = cp->tag_at(index);
2137   if (!tag.is_string()) {
2138     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2139   }
2140   oop str = cp->string_at(index, CHECK_NULL);
2141   return (jstring) JNIHandles::make_local(str);
2142 }
2143 JVM_END
2144 
2145 JVM_ENTRY(jstring, JVM_ConstantPoolGetUTF8At(JNIEnv *env, jobject obj, jobject unused, jint index))
2146 {
2147   JVMWrapper("JVM_ConstantPoolGetUTF8At");
2148   JvmtiVMObjectAllocEventCollector oam;
2149   constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2150   bounds_check(cp, index, CHECK_NULL);
2151   constantTag tag = cp->tag_at(index);
2152   if (!tag.is_symbol()) {
2153     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2154   }
2155   Symbol* sym = cp->symbol_at(index);
2156   Handle str = java_lang_String::create_from_symbol(sym, CHECK_NULL);
2157   return (jstring) JNIHandles::make_local(str());
2158 }
2159 JVM_END
2160 
2161 
2162 // Assertion support. //////////////////////////////////////////////////////////
2163 
2164 JVM_ENTRY(jboolean, JVM_DesiredAssertionStatus(JNIEnv *env, jclass unused, jclass cls))
2165   JVMWrapper("JVM_DesiredAssertionStatus");
2166   assert(cls != NULL, "bad class");
2167 
2168   oop r = JNIHandles::resolve(cls);
2169   assert(! java_lang_Class::is_primitive(r), "primitive classes not allowed");
2170   if (java_lang_Class::is_primitive(r)) return false;
2171 
2172   Klass* k = java_lang_Class::as_Klass(r);
2173   assert(k->oop_is_instance(), "must be an instance klass");
2174   if (! k->oop_is_instance()) return false;
2175 
2176   ResourceMark rm(THREAD);
2177   const char* name = k->name()->as_C_string();
2178   bool system_class = k->class_loader() == NULL;
2179   return JavaAssertions::enabled(name, system_class);
2180 
2181 JVM_END
2182 
2183 
2184 // Return a new AssertionStatusDirectives object with the fields filled in with
2185 // command-line assertion arguments (i.e., -ea, -da).
2186 JVM_ENTRY(jobject, JVM_AssertionStatusDirectives(JNIEnv *env, jclass unused))
2187   JVMWrapper("JVM_AssertionStatusDirectives");
2188   JvmtiVMObjectAllocEventCollector oam;
2189   oop asd = JavaAssertions::createAssertionStatusDirectives(CHECK_NULL);
2190   return JNIHandles::make_local(env, asd);
2191 JVM_END
2192 
2193 // Verification ////////////////////////////////////////////////////////////////////////////////
2194 
2195 // Reflection for the verifier /////////////////////////////////////////////////////////////////
2196 
2197 // RedefineClasses support: bug 6214132 caused verification to fail.
2198 // All functions from this section should call the jvmtiThreadSate function:
2199 //   Klass* class_to_verify_considering_redefinition(Klass* klass).
2200 // The function returns a Klass* of the _scratch_class if the verifier
2201 // was invoked in the middle of the class redefinition.
2202 // Otherwise it returns its argument value which is the _the_class Klass*.
2203 // Please, refer to the description in the jvmtiThreadSate.hpp.
2204 
2205 JVM_ENTRY(const char*, JVM_GetClassNameUTF(JNIEnv *env, jclass cls))
2206   JVMWrapper("JVM_GetClassNameUTF");
2207   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2208   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2209   return k->name()->as_utf8();
2210 JVM_END
2211 
2212 
2213 JVM_QUICK_ENTRY(void, JVM_GetClassCPTypes(JNIEnv *env, jclass cls, unsigned char *types))
2214   JVMWrapper("JVM_GetClassCPTypes");
2215   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2216   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2217   // types will have length zero if this is not an InstanceKlass
2218   // (length is determined by call to JVM_GetClassCPEntriesCount)
2219   if (k->oop_is_instance()) {
2220     ConstantPool* cp = InstanceKlass::cast(k)->constants();
2221     for (int index = cp->length() - 1; index >= 0; index--) {
2222       constantTag tag = cp->tag_at(index);
2223       types[index] = (tag.is_unresolved_klass()) ? JVM_CONSTANT_Class : tag.value();
2224   }
2225   }
2226 JVM_END
2227 
2228 
2229 JVM_QUICK_ENTRY(jint, JVM_GetClassCPEntriesCount(JNIEnv *env, jclass cls))
2230   JVMWrapper("JVM_GetClassCPEntriesCount");
2231   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2232   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2233   if (!k->oop_is_instance())
2234     return 0;
2235   return InstanceKlass::cast(k)->constants()->length();
2236 JVM_END
2237 
2238 
2239 JVM_QUICK_ENTRY(jint, JVM_GetClassFieldsCount(JNIEnv *env, jclass cls))
2240   JVMWrapper("JVM_GetClassFieldsCount");
2241   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2242   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2243   if (!k->oop_is_instance())
2244     return 0;
2245   return InstanceKlass::cast(k)->java_fields_count();
2246 JVM_END
2247 
2248 
2249 JVM_QUICK_ENTRY(jint, JVM_GetClassMethodsCount(JNIEnv *env, jclass cls))
2250   JVMWrapper("JVM_GetClassMethodsCount");
2251   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2252   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2253   if (!k->oop_is_instance())
2254     return 0;
2255   return InstanceKlass::cast(k)->methods()->length();
2256 JVM_END
2257 
2258 
2259 // The following methods, used for the verifier, are never called with
2260 // array klasses, so a direct cast to InstanceKlass is safe.
2261 // Typically, these methods are called in a loop with bounds determined
2262 // by the results of JVM_GetClass{Fields,Methods}Count, which return
2263 // zero for arrays.
2264 JVM_QUICK_ENTRY(void, JVM_GetMethodIxExceptionIndexes(JNIEnv *env, jclass cls, jint method_index, unsigned short *exceptions))
2265   JVMWrapper("JVM_GetMethodIxExceptionIndexes");
2266   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2267   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2268   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2269   int length = method->checked_exceptions_length();
2270   if (length > 0) {
2271     CheckedExceptionElement* table= method->checked_exceptions_start();
2272     for (int i = 0; i < length; i++) {
2273       exceptions[i] = table[i].class_cp_index;
2274     }
2275   }
2276 JVM_END
2277 
2278 
2279 JVM_QUICK_ENTRY(jint, JVM_GetMethodIxExceptionsCount(JNIEnv *env, jclass cls, jint method_index))
2280   JVMWrapper("JVM_GetMethodIxExceptionsCount");
2281   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2282   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2283   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2284   return method->checked_exceptions_length();
2285 JVM_END
2286 
2287 
2288 JVM_QUICK_ENTRY(void, JVM_GetMethodIxByteCode(JNIEnv *env, jclass cls, jint method_index, unsigned char *code))
2289   JVMWrapper("JVM_GetMethodIxByteCode");
2290   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2291   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2292   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2293   memcpy(code, method->code_base(), method->code_size());
2294 JVM_END
2295 
2296 
2297 JVM_QUICK_ENTRY(jint, JVM_GetMethodIxByteCodeLength(JNIEnv *env, jclass cls, jint method_index))
2298   JVMWrapper("JVM_GetMethodIxByteCodeLength");
2299   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2300   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2301   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2302   return method->code_size();
2303 JVM_END
2304 
2305 
2306 JVM_QUICK_ENTRY(void, JVM_GetMethodIxExceptionTableEntry(JNIEnv *env, jclass cls, jint method_index, jint entry_index, JVM_ExceptionTableEntryType *entry))
2307   JVMWrapper("JVM_GetMethodIxExceptionTableEntry");
2308   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2309   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2310   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2311   ExceptionTable extable(method);
2312   entry->start_pc   = extable.start_pc(entry_index);
2313   entry->end_pc     = extable.end_pc(entry_index);
2314   entry->handler_pc = extable.handler_pc(entry_index);
2315   entry->catchType  = extable.catch_type_index(entry_index);
2316 JVM_END
2317 
2318 
2319 JVM_QUICK_ENTRY(jint, JVM_GetMethodIxExceptionTableLength(JNIEnv *env, jclass cls, int method_index))
2320   JVMWrapper("JVM_GetMethodIxExceptionTableLength");
2321   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2322   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2323   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2324   return method->exception_table_length();
2325 JVM_END
2326 
2327 
2328 JVM_QUICK_ENTRY(jint, JVM_GetMethodIxModifiers(JNIEnv *env, jclass cls, int method_index))
2329   JVMWrapper("JVM_GetMethodIxModifiers");
2330   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2331   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2332   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2333   return method->access_flags().as_int() & JVM_RECOGNIZED_METHOD_MODIFIERS;
2334 JVM_END
2335 
2336 
2337 JVM_QUICK_ENTRY(jint, JVM_GetFieldIxModifiers(JNIEnv *env, jclass cls, int field_index))
2338   JVMWrapper("JVM_GetFieldIxModifiers");
2339   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2340   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2341   return InstanceKlass::cast(k)->field_access_flags(field_index) & JVM_RECOGNIZED_FIELD_MODIFIERS;
2342 JVM_END
2343 
2344 
2345 JVM_QUICK_ENTRY(jint, JVM_GetMethodIxLocalsCount(JNIEnv *env, jclass cls, int method_index))
2346   JVMWrapper("JVM_GetMethodIxLocalsCount");
2347   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2348   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2349   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2350   return method->max_locals();
2351 JVM_END
2352 
2353 
2354 JVM_QUICK_ENTRY(jint, JVM_GetMethodIxArgsSize(JNIEnv *env, jclass cls, int method_index))
2355   JVMWrapper("JVM_GetMethodIxArgsSize");
2356   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2357   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2358   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2359   return method->size_of_parameters();
2360 JVM_END
2361 
2362 
2363 JVM_QUICK_ENTRY(jint, JVM_GetMethodIxMaxStack(JNIEnv *env, jclass cls, int method_index))
2364   JVMWrapper("JVM_GetMethodIxMaxStack");
2365   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2366   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2367   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2368   return method->verifier_max_stack();
2369 JVM_END
2370 
2371 
2372 JVM_QUICK_ENTRY(jboolean, JVM_IsConstructorIx(JNIEnv *env, jclass cls, int method_index))
2373   JVMWrapper("JVM_IsConstructorIx");
2374   ResourceMark rm(THREAD);
2375   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2376   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2377   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2378   return method->name() == vmSymbols::object_initializer_name();
2379 JVM_END
2380 
2381 
2382 JVM_QUICK_ENTRY(jboolean, JVM_IsVMGeneratedMethodIx(JNIEnv *env, jclass cls, int method_index))
2383   JVMWrapper("JVM_IsVMGeneratedMethodIx");
2384   ResourceMark rm(THREAD);
2385   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2386   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2387   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2388   return method->is_overpass();
2389 JVM_END
2390 
2391 JVM_ENTRY(const char*, JVM_GetMethodIxNameUTF(JNIEnv *env, jclass cls, jint method_index))
2392   JVMWrapper("JVM_GetMethodIxIxUTF");
2393   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2394   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2395   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2396   return method->name()->as_utf8();
2397 JVM_END
2398 
2399 
2400 JVM_ENTRY(const char*, JVM_GetMethodIxSignatureUTF(JNIEnv *env, jclass cls, jint method_index))
2401   JVMWrapper("JVM_GetMethodIxSignatureUTF");
2402   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2403   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2404   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2405   return method->signature()->as_utf8();
2406 JVM_END
2407 
2408 /**
2409  * All of these JVM_GetCP-xxx methods are used by the old verifier to
2410  * read entries in the constant pool.  Since the old verifier always
2411  * works on a copy of the code, it will not see any rewriting that
2412  * may possibly occur in the middle of verification.  So it is important
2413  * that nothing it calls tries to use the cpCache instead of the raw
2414  * constant pool, so we must use cp->uncached_x methods when appropriate.
2415  */
2416 JVM_ENTRY(const char*, JVM_GetCPFieldNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2417   JVMWrapper("JVM_GetCPFieldNameUTF");
2418   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2419   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2420   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2421   switch (cp->tag_at(cp_index).value()) {
2422     case JVM_CONSTANT_Fieldref:
2423       return cp->uncached_name_ref_at(cp_index)->as_utf8();
2424     default:
2425       fatal("JVM_GetCPFieldNameUTF: illegal constant");
2426   }
2427   ShouldNotReachHere();
2428   return NULL;
2429 JVM_END
2430 
2431 
2432 JVM_ENTRY(const char*, JVM_GetCPMethodNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2433   JVMWrapper("JVM_GetCPMethodNameUTF");
2434   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2435   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2436   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2437   switch (cp->tag_at(cp_index).value()) {
2438     case JVM_CONSTANT_InterfaceMethodref:
2439     case JVM_CONSTANT_Methodref:
2440     case JVM_CONSTANT_NameAndType:  // for invokedynamic
2441       return cp->uncached_name_ref_at(cp_index)->as_utf8();
2442     default:
2443       fatal("JVM_GetCPMethodNameUTF: illegal constant");
2444   }
2445   ShouldNotReachHere();
2446   return NULL;
2447 JVM_END
2448 
2449 
2450 JVM_ENTRY(const char*, JVM_GetCPMethodSignatureUTF(JNIEnv *env, jclass cls, jint cp_index))
2451   JVMWrapper("JVM_GetCPMethodSignatureUTF");
2452   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2453   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2454   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2455   switch (cp->tag_at(cp_index).value()) {
2456     case JVM_CONSTANT_InterfaceMethodref:
2457     case JVM_CONSTANT_Methodref:
2458     case JVM_CONSTANT_NameAndType:  // for invokedynamic
2459       return cp->uncached_signature_ref_at(cp_index)->as_utf8();
2460     default:
2461       fatal("JVM_GetCPMethodSignatureUTF: illegal constant");
2462   }
2463   ShouldNotReachHere();
2464   return NULL;
2465 JVM_END
2466 
2467 
2468 JVM_ENTRY(const char*, JVM_GetCPFieldSignatureUTF(JNIEnv *env, jclass cls, jint cp_index))
2469   JVMWrapper("JVM_GetCPFieldSignatureUTF");
2470   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2471   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2472   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2473   switch (cp->tag_at(cp_index).value()) {
2474     case JVM_CONSTANT_Fieldref:
2475       return cp->uncached_signature_ref_at(cp_index)->as_utf8();
2476     default:
2477       fatal("JVM_GetCPFieldSignatureUTF: illegal constant");
2478   }
2479   ShouldNotReachHere();
2480   return NULL;
2481 JVM_END
2482 
2483 
2484 JVM_ENTRY(const char*, JVM_GetCPClassNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2485   JVMWrapper("JVM_GetCPClassNameUTF");
2486   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2487   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2488   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2489   Symbol* classname = cp->klass_name_at(cp_index);
2490   return classname->as_utf8();
2491 JVM_END
2492 
2493 
2494 JVM_ENTRY(const char*, JVM_GetCPFieldClassNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2495   JVMWrapper("JVM_GetCPFieldClassNameUTF");
2496   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2497   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2498   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2499   switch (cp->tag_at(cp_index).value()) {
2500     case JVM_CONSTANT_Fieldref: {
2501       int class_index = cp->uncached_klass_ref_index_at(cp_index);
2502       Symbol* classname = cp->klass_name_at(class_index);
2503       return classname->as_utf8();
2504     }
2505     default:
2506       fatal("JVM_GetCPFieldClassNameUTF: illegal constant");
2507   }
2508   ShouldNotReachHere();
2509   return NULL;
2510 JVM_END
2511 
2512 
2513 JVM_ENTRY(const char*, JVM_GetCPMethodClassNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2514   JVMWrapper("JVM_GetCPMethodClassNameUTF");
2515   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2516   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2517   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2518   switch (cp->tag_at(cp_index).value()) {
2519     case JVM_CONSTANT_Methodref:
2520     case JVM_CONSTANT_InterfaceMethodref: {
2521       int class_index = cp->uncached_klass_ref_index_at(cp_index);
2522       Symbol* classname = cp->klass_name_at(class_index);
2523       return classname->as_utf8();
2524     }
2525     default:
2526       fatal("JVM_GetCPMethodClassNameUTF: illegal constant");
2527   }
2528   ShouldNotReachHere();
2529   return NULL;
2530 JVM_END
2531 
2532 
2533 JVM_ENTRY(jint, JVM_GetCPFieldModifiers(JNIEnv *env, jclass cls, int cp_index, jclass called_cls))
2534   JVMWrapper("JVM_GetCPFieldModifiers");
2535   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2536   Klass* k_called = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(called_cls));
2537   k        = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2538   k_called = JvmtiThreadState::class_to_verify_considering_redefinition(k_called, thread);
2539   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2540   ConstantPool* cp_called = InstanceKlass::cast(k_called)->constants();
2541   switch (cp->tag_at(cp_index).value()) {
2542     case JVM_CONSTANT_Fieldref: {
2543       Symbol* name      = cp->uncached_name_ref_at(cp_index);
2544       Symbol* signature = cp->uncached_signature_ref_at(cp_index);
2545       for (JavaFieldStream fs(k_called); !fs.done(); fs.next()) {
2546         if (fs.name() == name && fs.signature() == signature) {
2547           return fs.access_flags().as_short() & JVM_RECOGNIZED_FIELD_MODIFIERS;
2548         }
2549       }
2550       return -1;
2551     }
2552     default:
2553       fatal("JVM_GetCPFieldModifiers: illegal constant");
2554   }
2555   ShouldNotReachHere();
2556   return 0;
2557 JVM_END
2558 
2559 
2560 JVM_QUICK_ENTRY(jint, JVM_GetCPMethodModifiers(JNIEnv *env, jclass cls, int cp_index, jclass called_cls))
2561   JVMWrapper("JVM_GetCPMethodModifiers");
2562   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2563   Klass* k_called = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(called_cls));
2564   k        = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2565   k_called = JvmtiThreadState::class_to_verify_considering_redefinition(k_called, thread);
2566   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2567   switch (cp->tag_at(cp_index).value()) {
2568     case JVM_CONSTANT_Methodref:
2569     case JVM_CONSTANT_InterfaceMethodref: {
2570       Symbol* name      = cp->uncached_name_ref_at(cp_index);
2571       Symbol* signature = cp->uncached_signature_ref_at(cp_index);
2572       Array<Method*>* methods = InstanceKlass::cast(k_called)->methods();
2573       int methods_count = methods->length();
2574       for (int i = 0; i < methods_count; i++) {
2575         Method* method = methods->at(i);
2576         if (method->name() == name && method->signature() == signature) {
2577             return method->access_flags().as_int() & JVM_RECOGNIZED_METHOD_MODIFIERS;
2578         }
2579       }
2580       return -1;
2581     }
2582     default:
2583       fatal("JVM_GetCPMethodModifiers: illegal constant");
2584   }
2585   ShouldNotReachHere();
2586   return 0;
2587 JVM_END
2588 
2589 
2590 // Misc //////////////////////////////////////////////////////////////////////////////////////////////
2591 
2592 JVM_LEAF(void, JVM_ReleaseUTF(const char *utf))
2593   // So long as UTF8::convert_to_utf8 returns resource strings, we don't have to do anything
2594 JVM_END
2595 
2596 
2597 JVM_ENTRY(jboolean, JVM_IsSameClassPackage(JNIEnv *env, jclass class1, jclass class2))
2598   JVMWrapper("JVM_IsSameClassPackage");
2599   oop class1_mirror = JNIHandles::resolve_non_null(class1);
2600   oop class2_mirror = JNIHandles::resolve_non_null(class2);
2601   Klass* klass1 = java_lang_Class::as_Klass(class1_mirror);
2602   Klass* klass2 = java_lang_Class::as_Klass(class2_mirror);
2603   return (jboolean) Reflection::is_same_class_package(klass1, klass2);
2604 JVM_END
2605 
2606 // Printing support //////////////////////////////////////////////////
2607 extern "C" {
2608 
2609 ATTRIBUTE_PRINTF(3, 0)
2610 int jio_vsnprintf(char *str, size_t count, const char *fmt, va_list args) {
2611   // see bug 4399518, 4417214
2612   if ((intptr_t)count <= 0) return -1;
2613 
2614   int result = vsnprintf(str, count, fmt, args);
2615   // Note: on truncation vsnprintf(3) on Unix returns numbers of
2616   // characters which would have been written had the buffer been large
2617   // enough; on Windows, it returns -1. We handle both cases here and
2618   // always return -1, and perform null termination.
2619   if ((result > 0 && (size_t)result >= count) || result == -1) {
2620     str[count - 1] = '\0';
2621     result = -1;
2622   }
2623 
2624   return result;
2625 }
2626 
2627 ATTRIBUTE_PRINTF(3, 0)
2628 int jio_snprintf(char *str, size_t count, const char *fmt, ...) {
2629   va_list args;
2630   int len;
2631   va_start(args, fmt);
2632   len = jio_vsnprintf(str, count, fmt, args);
2633   va_end(args);
2634   return len;
2635 }
2636 
2637 ATTRIBUTE_PRINTF(2,3)
2638 int jio_fprintf(FILE* f, const char *fmt, ...) {
2639   int len;
2640   va_list args;
2641   va_start(args, fmt);
2642   len = jio_vfprintf(f, fmt, args);
2643   va_end(args);
2644   return len;
2645 }
2646 
2647 ATTRIBUTE_PRINTF(2, 0)
2648 int jio_vfprintf(FILE* f, const char *fmt, va_list args) {
2649   if (Arguments::vfprintf_hook() != NULL) {
2650      return Arguments::vfprintf_hook()(f, fmt, args);
2651   } else {
2652     return vfprintf(f, fmt, args);
2653   }
2654 }
2655 
2656 ATTRIBUTE_PRINTF(1, 2)
2657 JNIEXPORT int jio_printf(const char *fmt, ...) {
2658   int len;
2659   va_list args;
2660   va_start(args, fmt);
2661   len = jio_vfprintf(defaultStream::output_stream(), fmt, args);
2662   va_end(args);
2663   return len;
2664 }
2665 
2666 
2667 // HotSpot specific jio method
2668 void jio_print(const char* s) {
2669   // Try to make this function as atomic as possible.
2670   if (Arguments::vfprintf_hook() != NULL) {
2671     jio_fprintf(defaultStream::output_stream(), "%s", s);
2672   } else {
2673     // Make an unused local variable to avoid warning from gcc 4.x compiler.
2674     size_t count = ::write(defaultStream::output_fd(), s, (int)strlen(s));
2675   }
2676 }
2677 
2678 } // Extern C
2679 
2680 // java.lang.Thread //////////////////////////////////////////////////////////////////////////////
2681 
2682 // In most of the JVM Thread support functions we need to be sure to lock the Threads_lock
2683 // to prevent the target thread from exiting after we have a pointer to the C++ Thread or
2684 // OSThread objects.  The exception to this rule is when the target object is the thread
2685 // doing the operation, in which case we know that the thread won't exit until the
2686 // operation is done (all exits being voluntary).  There are a few cases where it is
2687 // rather silly to do operations on yourself, like resuming yourself or asking whether
2688 // you are alive.  While these can still happen, they are not subject to deadlocks if
2689 // the lock is held while the operation occurs (this is not the case for suspend, for
2690 // instance), and are very unlikely.  Because IsAlive needs to be fast and its
2691 // implementation is local to this file, we always lock Threads_lock for that one.
2692 
2693 static void thread_entry(JavaThread* thread, TRAPS) {
2694   HandleMark hm(THREAD);
2695   Handle obj(THREAD, thread->threadObj());
2696   JavaValue result(T_VOID);
2697   JavaCalls::call_virtual(&result,
2698                           obj,
2699                           KlassHandle(THREAD, SystemDictionary::Thread_klass()),
2700                           vmSymbols::run_method_name(),
2701                           vmSymbols::void_method_signature(),
2702                           THREAD);
2703 }
2704 
2705 
2706 JVM_ENTRY(void, JVM_StartThread(JNIEnv* env, jobject jthread))
2707   JVMWrapper("JVM_StartThread");
2708   JavaThread *native_thread = NULL;
2709 
2710   // We cannot hold the Threads_lock when we throw an exception,
2711   // due to rank ordering issues. Example:  we might need to grab the
2712   // Heap_lock while we construct the exception.
2713   bool throw_illegal_thread_state = false;
2714 
2715   // We must release the Threads_lock before we can post a jvmti event
2716   // in Thread::start.
2717   {
2718     // Ensure that the C++ Thread and OSThread structures aren't freed before
2719     // we operate.
2720     MutexLocker mu(Threads_lock);
2721 
2722     // Since JDK 5 the java.lang.Thread threadStatus is used to prevent
2723     // re-starting an already started thread, so we should usually find
2724     // that the JavaThread is null. However for a JNI attached thread
2725     // there is a small window between the Thread object being created
2726     // (with its JavaThread set) and the update to its threadStatus, so we
2727     // have to check for this
2728     if (java_lang_Thread::thread(JNIHandles::resolve_non_null(jthread)) != NULL) {
2729       throw_illegal_thread_state = true;
2730     } else {
2731       // We could also check the stillborn flag to see if this thread was already stopped, but
2732       // for historical reasons we let the thread detect that itself when it starts running
2733 
2734       jlong size =
2735              java_lang_Thread::stackSize(JNIHandles::resolve_non_null(jthread));
2736       // Allocate the C++ Thread structure and create the native thread.  The
2737       // stack size retrieved from java is signed, but the constructor takes
2738       // size_t (an unsigned type), so avoid passing negative values which would
2739       // result in really large stacks.
2740       size_t sz = size > 0 ? (size_t) size : 0;
2741       native_thread = new JavaThread(&thread_entry, sz);
2742 
2743       // At this point it may be possible that no osthread was created for the
2744       // JavaThread due to lack of memory. Check for this situation and throw
2745       // an exception if necessary. Eventually we may want to change this so
2746       // that we only grab the lock if the thread was created successfully -
2747       // then we can also do this check and throw the exception in the
2748       // JavaThread constructor.
2749       if (native_thread->osthread() != NULL) {
2750         // Note: the current thread is not being used within "prepare".
2751         native_thread->prepare(jthread);
2752       }
2753     }
2754   }
2755 
2756   if (throw_illegal_thread_state) {
2757     THROW(vmSymbols::java_lang_IllegalThreadStateException());
2758   }
2759 
2760   assert(native_thread != NULL, "Starting null thread?");
2761 
2762   if (native_thread->osthread() == NULL) {
2763     // No one should hold a reference to the 'native_thread'.
2764     delete native_thread;
2765     if (JvmtiExport::should_post_resource_exhausted()) {
2766       JvmtiExport::post_resource_exhausted(
2767         JVMTI_RESOURCE_EXHAUSTED_OOM_ERROR | JVMTI_RESOURCE_EXHAUSTED_THREADS,
2768         os::native_thread_creation_failed_msg());
2769     }
2770     THROW_MSG(vmSymbols::java_lang_OutOfMemoryError(),
2771               os::native_thread_creation_failed_msg());
2772   }
2773 
2774   Thread::start(native_thread);
2775 
2776 JVM_END
2777 
2778 // JVM_Stop is implemented using a VM_Operation, so threads are forced to safepoints
2779 // before the quasi-asynchronous exception is delivered.  This is a little obtrusive,
2780 // but is thought to be reliable and simple. In the case, where the receiver is the
2781 // same thread as the sender, no safepoint is needed.
2782 JVM_ENTRY(void, JVM_StopThread(JNIEnv* env, jobject jthread, jobject throwable))
2783   JVMWrapper("JVM_StopThread");
2784 
2785   oop java_throwable = JNIHandles::resolve(throwable);
2786   if (java_throwable == NULL) {
2787     THROW(vmSymbols::java_lang_NullPointerException());
2788   }
2789   oop java_thread = JNIHandles::resolve_non_null(jthread);
2790   JavaThread* receiver = java_lang_Thread::thread(java_thread);
2791   Events::log_exception(JavaThread::current(),
2792                         "JVM_StopThread thread JavaThread " INTPTR_FORMAT " as oop " INTPTR_FORMAT " [exception " INTPTR_FORMAT "]",
2793                         p2i(receiver), p2i((address)java_thread), p2i(throwable));
2794   // First check if thread is alive
2795   if (receiver != NULL) {
2796     // Check if exception is getting thrown at self (use oop equality, since the
2797     // target object might exit)
2798     if (java_thread == thread->threadObj()) {
2799       THROW_OOP(java_throwable);
2800     } else {
2801       // Enques a VM_Operation to stop all threads and then deliver the exception...
2802       Thread::send_async_exception(java_thread, JNIHandles::resolve(throwable));
2803     }
2804   }
2805   else {
2806     // Either:
2807     // - target thread has not been started before being stopped, or
2808     // - target thread already terminated
2809     // We could read the threadStatus to determine which case it is
2810     // but that is overkill as it doesn't matter. We must set the
2811     // stillborn flag for the first case, and if the thread has already
2812     // exited setting this flag has no affect
2813     java_lang_Thread::set_stillborn(java_thread);
2814   }
2815 JVM_END
2816 
2817 
2818 JVM_ENTRY(jboolean, JVM_IsThreadAlive(JNIEnv* env, jobject jthread))
2819   JVMWrapper("JVM_IsThreadAlive");
2820 
2821   oop thread_oop = JNIHandles::resolve_non_null(jthread);
2822   return java_lang_Thread::is_alive(thread_oop);
2823 JVM_END
2824 
2825 
2826 JVM_ENTRY(void, JVM_SuspendThread(JNIEnv* env, jobject jthread))
2827   JVMWrapper("JVM_SuspendThread");
2828   oop java_thread = JNIHandles::resolve_non_null(jthread);
2829   JavaThread* receiver = java_lang_Thread::thread(java_thread);
2830 
2831   if (receiver != NULL) {
2832     // thread has run and has not exited (still on threads list)
2833 
2834     {
2835       MutexLockerEx ml(receiver->SR_lock(), Mutex::_no_safepoint_check_flag);
2836       if (receiver->is_external_suspend()) {
2837         // Don't allow nested external suspend requests. We can't return
2838         // an error from this interface so just ignore the problem.
2839         return;
2840       }
2841       if (receiver->is_exiting()) { // thread is in the process of exiting
2842         return;
2843       }
2844       receiver->set_external_suspend();
2845     }
2846 
2847     // java_suspend() will catch threads in the process of exiting
2848     // and will ignore them.
2849     receiver->java_suspend();
2850 
2851     // It would be nice to have the following assertion in all the
2852     // time, but it is possible for a racing resume request to have
2853     // resumed this thread right after we suspended it. Temporarily
2854     // enable this assertion if you are chasing a different kind of
2855     // bug.
2856     //
2857     // assert(java_lang_Thread::thread(receiver->threadObj()) == NULL ||
2858     //   receiver->is_being_ext_suspended(), "thread is not suspended");
2859   }
2860 JVM_END
2861 
2862 
2863 JVM_ENTRY(void, JVM_ResumeThread(JNIEnv* env, jobject jthread))
2864   JVMWrapper("JVM_ResumeThread");
2865   // Ensure that the C++ Thread and OSThread structures aren't freed before we operate.
2866   // We need to *always* get the threads lock here, since this operation cannot be allowed during
2867   // a safepoint. The safepoint code relies on suspending a thread to examine its state. If other
2868   // threads randomly resumes threads, then a thread might not be suspended when the safepoint code
2869   // looks at it.
2870   MutexLocker ml(Threads_lock);
2871   JavaThread* thr = java_lang_Thread::thread(JNIHandles::resolve_non_null(jthread));
2872   if (thr != NULL) {
2873     // the thread has run and is not in the process of exiting
2874     thr->java_resume();
2875   }
2876 JVM_END
2877 
2878 
2879 JVM_ENTRY(void, JVM_SetThreadPriority(JNIEnv* env, jobject jthread, jint prio))
2880   JVMWrapper("JVM_SetThreadPriority");
2881   // Ensure that the C++ Thread and OSThread structures aren't freed before we operate
2882   MutexLocker ml(Threads_lock);
2883   oop java_thread = JNIHandles::resolve_non_null(jthread);
2884   java_lang_Thread::set_priority(java_thread, (ThreadPriority)prio);
2885   JavaThread* thr = java_lang_Thread::thread(java_thread);
2886   if (thr != NULL) {                  // Thread not yet started; priority pushed down when it is
2887     Thread::set_priority(thr, (ThreadPriority)prio);
2888   }
2889 JVM_END
2890 
2891 
2892 JVM_ENTRY(void, JVM_Yield(JNIEnv *env, jclass threadClass))
2893   JVMWrapper("JVM_Yield");
2894   if (os::dont_yield()) return;
2895   HOTSPOT_THREAD_YIELD();
2896 
2897   // When ConvertYieldToSleep is off (default), this matches the classic VM use of yield.
2898   // Critical for similar threading behaviour
2899   if (ConvertYieldToSleep) {
2900     os::sleep(thread, MinSleepInterval, false);
2901   } else {
2902     os::naked_yield();
2903   }
2904 JVM_END
2905 
2906 
2907 JVM_ENTRY(void, JVM_Sleep(JNIEnv* env, jclass threadClass, jlong millis))
2908   JVMWrapper("JVM_Sleep");
2909 
2910   if (millis < 0) {
2911     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "timeout value is negative");
2912   }
2913 
2914   if (Thread::is_interrupted (THREAD, true) && !HAS_PENDING_EXCEPTION) {
2915     THROW_MSG(vmSymbols::java_lang_InterruptedException(), "sleep interrupted");
2916   }
2917 
2918   // Save current thread state and restore it at the end of this block.
2919   // And set new thread state to SLEEPING.
2920   JavaThreadSleepState jtss(thread);
2921 
2922   HOTSPOT_THREAD_SLEEP_BEGIN(millis);
2923 
2924   EventThreadSleep event;
2925 
2926   if (millis == 0) {
2927     // When ConvertSleepToYield is on, this matches the classic VM implementation of
2928     // JVM_Sleep. Critical for similar threading behaviour (Win32)
2929     // It appears that in certain GUI contexts, it may be beneficial to do a short sleep
2930     // for SOLARIS
2931     if (ConvertSleepToYield) {
2932       os::naked_yield();
2933     } else {
2934       ThreadState old_state = thread->osthread()->get_state();
2935       thread->osthread()->set_state(SLEEPING);
2936       os::sleep(thread, MinSleepInterval, false);
2937       thread->osthread()->set_state(old_state);
2938     }
2939   } else {
2940     ThreadState old_state = thread->osthread()->get_state();
2941     thread->osthread()->set_state(SLEEPING);
2942     if (os::sleep(thread, millis, true) == OS_INTRPT) {
2943       // An asynchronous exception (e.g., ThreadDeathException) could have been thrown on
2944       // us while we were sleeping. We do not overwrite those.
2945       if (!HAS_PENDING_EXCEPTION) {
2946         if (event.should_commit()) {
2947           event.set_time(millis);
2948           event.commit();
2949         }
2950         HOTSPOT_THREAD_SLEEP_END(1);
2951 
2952         // TODO-FIXME: THROW_MSG returns which means we will not call set_state()
2953         // to properly restore the thread state.  That's likely wrong.
2954         THROW_MSG(vmSymbols::java_lang_InterruptedException(), "sleep interrupted");
2955       }
2956     }
2957     thread->osthread()->set_state(old_state);
2958   }
2959   if (event.should_commit()) {
2960     event.set_time(millis);
2961     event.commit();
2962   }
2963   HOTSPOT_THREAD_SLEEP_END(0);
2964 JVM_END
2965 
2966 JVM_ENTRY(jobject, JVM_CurrentThread(JNIEnv* env, jclass threadClass))
2967   JVMWrapper("JVM_CurrentThread");
2968   oop jthread = thread->threadObj();
2969   assert (thread != NULL, "no current thread!");
2970   return JNIHandles::make_local(env, jthread);
2971 JVM_END
2972 
2973 
2974 JVM_ENTRY(jint, JVM_CountStackFrames(JNIEnv* env, jobject jthread))
2975   JVMWrapper("JVM_CountStackFrames");
2976 
2977   // Ensure that the C++ Thread and OSThread structures aren't freed before we operate
2978   oop java_thread = JNIHandles::resolve_non_null(jthread);
2979   bool throw_illegal_thread_state = false;
2980   int count = 0;
2981 
2982   {
2983     MutexLockerEx ml(thread->threadObj() == java_thread ? NULL : Threads_lock);
2984     // We need to re-resolve the java_thread, since a GC might have happened during the
2985     // acquire of the lock
2986     JavaThread* thr = java_lang_Thread::thread(JNIHandles::resolve_non_null(jthread));
2987 
2988     if (thr == NULL) {
2989       // do nothing
2990     } else if(! thr->is_external_suspend() || ! thr->frame_anchor()->walkable()) {
2991       // Check whether this java thread has been suspended already. If not, throws
2992       // IllegalThreadStateException. We defer to throw that exception until
2993       // Threads_lock is released since loading exception class has to leave VM.
2994       // The correct way to test a thread is actually suspended is
2995       // wait_for_ext_suspend_completion(), but we can't call that while holding
2996       // the Threads_lock. The above tests are sufficient for our purposes
2997       // provided the walkability of the stack is stable - which it isn't
2998       // 100% but close enough for most practical purposes.
2999       throw_illegal_thread_state = true;
3000     } else {
3001       // Count all java activation, i.e., number of vframes
3002       for(vframeStream vfst(thr); !vfst.at_end(); vfst.next()) {
3003         // Native frames are not counted
3004         if (!vfst.method()->is_native()) count++;
3005        }
3006     }
3007   }
3008 
3009   if (throw_illegal_thread_state) {
3010     THROW_MSG_0(vmSymbols::java_lang_IllegalThreadStateException(),
3011                 "this thread is not suspended");
3012   }
3013   return count;
3014 JVM_END
3015 
3016 // Consider: A better way to implement JVM_Interrupt() is to acquire
3017 // Threads_lock to resolve the jthread into a Thread pointer, fetch
3018 // Thread->platformevent, Thread->native_thr, Thread->parker, etc.,
3019 // drop Threads_lock, and the perform the unpark() and thr_kill() operations
3020 // outside the critical section.  Threads_lock is hot so we want to minimize
3021 // the hold-time.  A cleaner interface would be to decompose interrupt into
3022 // two steps.  The 1st phase, performed under Threads_lock, would return
3023 // a closure that'd be invoked after Threads_lock was dropped.
3024 // This tactic is safe as PlatformEvent and Parkers are type-stable (TSM) and
3025 // admit spurious wakeups.
3026 
3027 JVM_ENTRY(void, JVM_Interrupt(JNIEnv* env, jobject jthread))
3028   JVMWrapper("JVM_Interrupt");
3029 
3030   // Ensure that the C++ Thread and OSThread structures aren't freed before we operate
3031   oop java_thread = JNIHandles::resolve_non_null(jthread);
3032   MutexLockerEx ml(thread->threadObj() == java_thread ? NULL : Threads_lock);
3033   // We need to re-resolve the java_thread, since a GC might have happened during the
3034   // acquire of the lock
3035   JavaThread* thr = java_lang_Thread::thread(JNIHandles::resolve_non_null(jthread));
3036   if (thr != NULL) {
3037     Thread::interrupt(thr);
3038   }
3039 JVM_END
3040 
3041 
3042 JVM_QUICK_ENTRY(jboolean, JVM_IsInterrupted(JNIEnv* env, jobject jthread, jboolean clear_interrupted))
3043   JVMWrapper("JVM_IsInterrupted");
3044 
3045   // Ensure that the C++ Thread and OSThread structures aren't freed before we operate
3046   oop java_thread = JNIHandles::resolve_non_null(jthread);
3047   MutexLockerEx ml(thread->threadObj() == java_thread ? NULL : Threads_lock);
3048   // We need to re-resolve the java_thread, since a GC might have happened during the
3049   // acquire of the lock
3050   JavaThread* thr = java_lang_Thread::thread(JNIHandles::resolve_non_null(jthread));
3051   if (thr == NULL) {
3052     return JNI_FALSE;
3053   } else {
3054     return (jboolean) Thread::is_interrupted(thr, clear_interrupted != 0);
3055   }
3056 JVM_END
3057 
3058 
3059 // Return true iff the current thread has locked the object passed in
3060 
3061 JVM_ENTRY(jboolean, JVM_HoldsLock(JNIEnv* env, jclass threadClass, jobject obj))
3062   JVMWrapper("JVM_HoldsLock");
3063   assert(THREAD->is_Java_thread(), "sanity check");
3064   if (obj == NULL) {
3065     THROW_(vmSymbols::java_lang_NullPointerException(), JNI_FALSE);
3066   }
3067   Handle h_obj(THREAD, JNIHandles::resolve(obj));
3068   return ObjectSynchronizer::current_thread_holds_lock((JavaThread*)THREAD, h_obj);
3069 JVM_END
3070 
3071 
3072 JVM_ENTRY(void, JVM_DumpAllStacks(JNIEnv* env, jclass))
3073   JVMWrapper("JVM_DumpAllStacks");
3074   VM_PrintThreads op;
3075   VMThread::execute(&op);
3076   if (JvmtiExport::should_post_data_dump()) {
3077     JvmtiExport::post_data_dump();
3078   }
3079 JVM_END
3080 
3081 JVM_ENTRY(void, JVM_SetNativeThreadName(JNIEnv* env, jobject jthread, jstring name))
3082   JVMWrapper("JVM_SetNativeThreadName");
3083   ResourceMark rm(THREAD);
3084   oop java_thread = JNIHandles::resolve_non_null(jthread);
3085   JavaThread* thr = java_lang_Thread::thread(java_thread);
3086   // Thread naming only supported for the current thread, doesn't work for
3087   // target threads.
3088   if (Thread::current() == thr && !thr->has_attached_via_jni()) {
3089     // we don't set the name of an attached thread to avoid stepping
3090     // on other programs
3091     const char *thread_name = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(name));
3092     os::set_native_thread_name(thread_name);
3093   }
3094 JVM_END
3095 
3096 // java.lang.SecurityManager ///////////////////////////////////////////////////////////////////////
3097 
3098 static bool is_trusted_frame(JavaThread* jthread, vframeStream* vfst) {
3099   assert(jthread->is_Java_thread(), "must be a Java thread");
3100   if (jthread->privileged_stack_top() == NULL) return false;
3101   if (jthread->privileged_stack_top()->frame_id() == vfst->frame_id()) {
3102     oop loader = jthread->privileged_stack_top()->class_loader();
3103     if (loader == NULL) return true;
3104     bool trusted = java_lang_ClassLoader::is_trusted_loader(loader);
3105     if (trusted) return true;
3106   }
3107   return false;
3108 }
3109 
3110 JVM_ENTRY(jclass, JVM_CurrentLoadedClass(JNIEnv *env))
3111   JVMWrapper("JVM_CurrentLoadedClass");
3112   ResourceMark rm(THREAD);
3113 
3114   for (vframeStream vfst(thread); !vfst.at_end(); vfst.next()) {
3115     // if a method in a class in a trusted loader is in a doPrivileged, return NULL
3116     bool trusted = is_trusted_frame(thread, &vfst);
3117     if (trusted) return NULL;
3118 
3119     Method* m = vfst.method();
3120     if (!m->is_native()) {
3121       InstanceKlass* holder = m->method_holder();
3122       oop loader = holder->class_loader();
3123       if (loader != NULL && !java_lang_ClassLoader::is_trusted_loader(loader)) {
3124         return (jclass) JNIHandles::make_local(env, holder->java_mirror());
3125       }
3126     }
3127   }
3128   return NULL;
3129 JVM_END
3130 
3131 
3132 JVM_ENTRY(jobject, JVM_CurrentClassLoader(JNIEnv *env))
3133   JVMWrapper("JVM_CurrentClassLoader");
3134   ResourceMark rm(THREAD);
3135 
3136   for (vframeStream vfst(thread); !vfst.at_end(); vfst.next()) {
3137 
3138     // if a method in a class in a trusted loader is in a doPrivileged, return NULL
3139     bool trusted = is_trusted_frame(thread, &vfst);
3140     if (trusted) return NULL;
3141 
3142     Method* m = vfst.method();
3143     if (!m->is_native()) {
3144       InstanceKlass* holder = m->method_holder();
3145       assert(holder->is_klass(), "just checking");
3146       oop loader = holder->class_loader();
3147       if (loader != NULL && !java_lang_ClassLoader::is_trusted_loader(loader)) {
3148         return JNIHandles::make_local(env, loader);
3149       }
3150     }
3151   }
3152   return NULL;
3153 JVM_END
3154 
3155 
3156 JVM_ENTRY(jobjectArray, JVM_GetClassContext(JNIEnv *env))
3157   JVMWrapper("JVM_GetClassContext");
3158   ResourceMark rm(THREAD);
3159   JvmtiVMObjectAllocEventCollector oam;
3160   vframeStream vfst(thread);
3161 
3162   if (SystemDictionary::reflect_CallerSensitive_klass() != NULL) {
3163     // This must only be called from SecurityManager.getClassContext
3164     Method* m = vfst.method();
3165     if (!(m->method_holder() == SystemDictionary::SecurityManager_klass() &&
3166           m->name()          == vmSymbols::getClassContext_name() &&
3167           m->signature()     == vmSymbols::void_class_array_signature())) {
3168       THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), "JVM_GetClassContext must only be called from SecurityManager.getClassContext");
3169     }
3170   }
3171 
3172   // Collect method holders
3173   GrowableArray<KlassHandle>* klass_array = new GrowableArray<KlassHandle>();
3174   for (; !vfst.at_end(); vfst.security_next()) {
3175     Method* m = vfst.method();
3176     // Native frames are not returned
3177     if (!m->is_ignored_by_security_stack_walk() && !m->is_native()) {
3178       Klass* holder = m->method_holder();
3179       assert(holder->is_klass(), "just checking");
3180       klass_array->append(holder);
3181     }
3182   }
3183 
3184   // Create result array of type [Ljava/lang/Class;
3185   objArrayOop result = oopFactory::new_objArray(SystemDictionary::Class_klass(), klass_array->length(), CHECK_NULL);
3186   // Fill in mirrors corresponding to method holders
3187   for (int i = 0; i < klass_array->length(); i++) {
3188     result->obj_at_put(i, klass_array->at(i)->java_mirror());
3189   }
3190 
3191   return (jobjectArray) JNIHandles::make_local(env, result);
3192 JVM_END
3193 
3194 
3195 JVM_ENTRY(jint, JVM_ClassDepth(JNIEnv *env, jstring name))
3196   JVMWrapper("JVM_ClassDepth");
3197   ResourceMark rm(THREAD);
3198   Handle h_name (THREAD, JNIHandles::resolve_non_null(name));
3199   Handle class_name_str = java_lang_String::internalize_classname(h_name, CHECK_0);
3200 
3201   const char* str = java_lang_String::as_utf8_string(class_name_str());
3202   TempNewSymbol class_name_sym = SymbolTable::probe(str, (int)strlen(str));
3203   if (class_name_sym == NULL) {
3204     return -1;
3205   }
3206 
3207   int depth = 0;
3208 
3209   for(vframeStream vfst(thread); !vfst.at_end(); vfst.next()) {
3210     if (!vfst.method()->is_native()) {
3211       InstanceKlass* holder = vfst.method()->method_holder();
3212       assert(holder->is_klass(), "just checking");
3213       if (holder->name() == class_name_sym) {
3214         return depth;
3215       }
3216       depth++;
3217     }
3218   }
3219   return -1;
3220 JVM_END
3221 
3222 
3223 JVM_ENTRY(jint, JVM_ClassLoaderDepth(JNIEnv *env))
3224   JVMWrapper("JVM_ClassLoaderDepth");
3225   ResourceMark rm(THREAD);
3226   int depth = 0;
3227   for (vframeStream vfst(thread); !vfst.at_end(); vfst.next()) {
3228     // if a method in a class in a trusted loader is in a doPrivileged, return -1
3229     bool trusted = is_trusted_frame(thread, &vfst);
3230     if (trusted) return -1;
3231 
3232     Method* m = vfst.method();
3233     if (!m->is_native()) {
3234       InstanceKlass* holder = m->method_holder();
3235       assert(holder->is_klass(), "just checking");
3236       oop loader = holder->class_loader();
3237       if (loader != NULL && !java_lang_ClassLoader::is_trusted_loader(loader)) {
3238         return depth;
3239       }
3240       depth++;
3241     }
3242   }
3243   return -1;
3244 JVM_END
3245 
3246 
3247 // java.lang.Package ////////////////////////////////////////////////////////////////
3248 
3249 
3250 JVM_ENTRY(jstring, JVM_GetSystemPackage(JNIEnv *env, jstring name))
3251   JVMWrapper("JVM_GetSystemPackage");
3252   ResourceMark rm(THREAD);
3253   JvmtiVMObjectAllocEventCollector oam;
3254   char* str = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(name));
3255   oop result = ClassLoader::get_system_package(str, CHECK_NULL);
3256   return (jstring) JNIHandles::make_local(result);
3257 JVM_END
3258 
3259 
3260 JVM_ENTRY(jobjectArray, JVM_GetSystemPackages(JNIEnv *env))
3261   JVMWrapper("JVM_GetSystemPackages");
3262   JvmtiVMObjectAllocEventCollector oam;
3263   objArrayOop result = ClassLoader::get_system_packages(CHECK_NULL);
3264   return (jobjectArray) JNIHandles::make_local(result);
3265 JVM_END
3266 
3267 
3268 // ObjectInputStream ///////////////////////////////////////////////////////////////
3269 
3270 bool force_verify_field_access(Klass* current_class, Klass* field_class, AccessFlags access, bool classloader_only) {
3271   if (current_class == NULL) {
3272     return true;
3273   }
3274   if ((current_class == field_class) || access.is_public()) {
3275     return true;
3276   }
3277 
3278   if (access.is_protected()) {
3279     // See if current_class is a subclass of field_class
3280     if (current_class->is_subclass_of(field_class)) {
3281       return true;
3282     }
3283   }
3284 
3285   return (!access.is_private() && InstanceKlass::cast(current_class)->is_same_class_package(field_class));
3286 }
3287 
3288 // Return the first non-null class loader up the execution stack, or null
3289 // if only code from the null class loader is on the stack.
3290 
3291 JVM_ENTRY(jobject, JVM_LatestUserDefinedLoader(JNIEnv *env))
3292   for (vframeStream vfst(thread); !vfst.at_end(); vfst.next()) {
3293     vfst.skip_reflection_related_frames(); // Only needed for 1.4 reflection
3294     oop loader = vfst.method()->method_holder()->class_loader();
3295     if (loader != NULL) {
3296       return JNIHandles::make_local(env, loader);
3297     }
3298   }
3299   return NULL;
3300 JVM_END
3301 
3302 
3303 // Array ///////////////////////////////////////////////////////////////////////////////////////////
3304 
3305 
3306 // resolve array handle and check arguments
3307 static inline arrayOop check_array(JNIEnv *env, jobject arr, bool type_array_only, TRAPS) {
3308   if (arr == NULL) {
3309     THROW_0(vmSymbols::java_lang_NullPointerException());
3310   }
3311   oop a = JNIHandles::resolve_non_null(arr);
3312   if (!a->is_array()) {
3313     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Argument is not an array");
3314   } else if (type_array_only && !a->is_typeArray()) {
3315     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Argument is not an array of primitive type");
3316   }
3317   return arrayOop(a);
3318 }
3319 
3320 
3321 JVM_ENTRY(jint, JVM_GetArrayLength(JNIEnv *env, jobject arr))
3322   JVMWrapper("JVM_GetArrayLength");
3323   arrayOop a = check_array(env, arr, false, CHECK_0);
3324   return a->length();
3325 JVM_END
3326 
3327 
3328 JVM_ENTRY(jobject, JVM_GetArrayElement(JNIEnv *env, jobject arr, jint index))
3329   JVMWrapper("JVM_Array_Get");
3330   JvmtiVMObjectAllocEventCollector oam;
3331   arrayOop a = check_array(env, arr, false, CHECK_NULL);
3332   jvalue value;
3333   BasicType type = Reflection::array_get(&value, a, index, CHECK_NULL);
3334   oop box = Reflection::box(&value, type, CHECK_NULL);
3335   return JNIHandles::make_local(env, box);
3336 JVM_END
3337 
3338 
3339 JVM_ENTRY(jvalue, JVM_GetPrimitiveArrayElement(JNIEnv *env, jobject arr, jint index, jint wCode))
3340   JVMWrapper("JVM_GetPrimitiveArrayElement");
3341   jvalue value;
3342   value.i = 0; // to initialize value before getting used in CHECK
3343   arrayOop a = check_array(env, arr, true, CHECK_(value));
3344   assert(a->is_typeArray(), "just checking");
3345   BasicType type = Reflection::array_get(&value, a, index, CHECK_(value));
3346   BasicType wide_type = (BasicType) wCode;
3347   if (type != wide_type) {
3348     Reflection::widen(&value, type, wide_type, CHECK_(value));
3349   }
3350   return value;
3351 JVM_END
3352 
3353 
3354 JVM_ENTRY(void, JVM_SetArrayElement(JNIEnv *env, jobject arr, jint index, jobject val))
3355   JVMWrapper("JVM_SetArrayElement");
3356   arrayOop a = check_array(env, arr, false, CHECK);
3357   oop box = JNIHandles::resolve(val);
3358   jvalue value;
3359   value.i = 0; // to initialize value before getting used in CHECK
3360   BasicType value_type;
3361   if (a->is_objArray()) {
3362     // Make sure we do no unbox e.g. java/lang/Integer instances when storing into an object array
3363     value_type = Reflection::unbox_for_regular_object(box, &value);
3364   } else {
3365     value_type = Reflection::unbox_for_primitive(box, &value, CHECK);
3366   }
3367   Reflection::array_set(&value, a, index, value_type, CHECK);
3368 JVM_END
3369 
3370 
3371 JVM_ENTRY(void, JVM_SetPrimitiveArrayElement(JNIEnv *env, jobject arr, jint index, jvalue v, unsigned char vCode))
3372   JVMWrapper("JVM_SetPrimitiveArrayElement");
3373   arrayOop a = check_array(env, arr, true, CHECK);
3374   assert(a->is_typeArray(), "just checking");
3375   BasicType value_type = (BasicType) vCode;
3376   Reflection::array_set(&v, a, index, value_type, CHECK);
3377 JVM_END
3378 
3379 
3380 JVM_ENTRY(jobject, JVM_NewArray(JNIEnv *env, jclass eltClass, jint length))
3381   JVMWrapper("JVM_NewArray");
3382   JvmtiVMObjectAllocEventCollector oam;
3383   oop element_mirror = JNIHandles::resolve(eltClass);
3384   oop result = Reflection::reflect_new_array(element_mirror, length, CHECK_NULL);
3385   return JNIHandles::make_local(env, result);
3386 JVM_END
3387 
3388 
3389 JVM_ENTRY(jobject, JVM_NewMultiArray(JNIEnv *env, jclass eltClass, jintArray dim))
3390   JVMWrapper("JVM_NewMultiArray");
3391   JvmtiVMObjectAllocEventCollector oam;
3392   arrayOop dim_array = check_array(env, dim, true, CHECK_NULL);
3393   oop element_mirror = JNIHandles::resolve(eltClass);
3394   assert(dim_array->is_typeArray(), "just checking");
3395   oop result = Reflection::reflect_new_multi_array(element_mirror, typeArrayOop(dim_array), CHECK_NULL);
3396   return JNIHandles::make_local(env, result);
3397 JVM_END
3398 
3399 
3400 // Library support ///////////////////////////////////////////////////////////////////////////
3401 
3402 JVM_ENTRY_NO_ENV(void*, JVM_LoadLibrary(const char* name))
3403   //%note jvm_ct
3404   JVMWrapper2("JVM_LoadLibrary (%s)", name);
3405   char ebuf[1024];
3406   void *load_result;
3407   {
3408     ThreadToNativeFromVM ttnfvm(thread);
3409     load_result = os::dll_load(name, ebuf, sizeof ebuf);
3410   }
3411   if (load_result == NULL) {
3412     char msg[1024];
3413     jio_snprintf(msg, sizeof msg, "%s: %s", name, ebuf);
3414     // Since 'ebuf' may contain a string encoded using
3415     // platform encoding scheme, we need to pass
3416     // Exceptions::unsafe_to_utf8 to the new_exception method
3417     // as the last argument. See bug 6367357.
3418     Handle h_exception =
3419       Exceptions::new_exception(thread,
3420                                 vmSymbols::java_lang_UnsatisfiedLinkError(),
3421                                 msg, Exceptions::unsafe_to_utf8);
3422 
3423     THROW_HANDLE_0(h_exception);
3424   }
3425   return load_result;
3426 JVM_END
3427 
3428 
3429 JVM_LEAF(void, JVM_UnloadLibrary(void* handle))
3430   JVMWrapper("JVM_UnloadLibrary");
3431   os::dll_unload(handle);
3432 JVM_END
3433 
3434 
3435 JVM_LEAF(void*, JVM_FindLibraryEntry(void* handle, const char* name))
3436   JVMWrapper2("JVM_FindLibraryEntry (%s)", name);
3437   return os::dll_lookup(handle, name);
3438 JVM_END
3439 
3440 
3441 // JNI version ///////////////////////////////////////////////////////////////////////////////
3442 
3443 JVM_LEAF(jboolean, JVM_IsSupportedJNIVersion(jint version))
3444   JVMWrapper2("JVM_IsSupportedJNIVersion (%d)", version);
3445   return Threads::is_supported_jni_version_including_1_1(version);
3446 JVM_END
3447 
3448 
3449 // String support ///////////////////////////////////////////////////////////////////////////
3450 
3451 JVM_ENTRY(jstring, JVM_InternString(JNIEnv *env, jstring str))
3452   JVMWrapper("JVM_InternString");
3453   JvmtiVMObjectAllocEventCollector oam;
3454   if (str == NULL) return NULL;
3455   oop string = JNIHandles::resolve_non_null(str);
3456   oop result = StringTable::intern(string, CHECK_NULL);
3457   return (jstring) JNIHandles::make_local(env, result);
3458 JVM_END
3459 
3460 
3461 // Raw monitor support //////////////////////////////////////////////////////////////////////
3462 
3463 // The lock routine below calls lock_without_safepoint_check in order to get a raw lock
3464 // without interfering with the safepoint mechanism. The routines are not JVM_LEAF because
3465 // they might be called by non-java threads. The JVM_LEAF installs a NoHandleMark check
3466 // that only works with java threads.
3467 
3468 
3469 JNIEXPORT void* JNICALL JVM_RawMonitorCreate(void) {
3470   VM_Exit::block_if_vm_exited();
3471   JVMWrapper("JVM_RawMonitorCreate");
3472   return new Mutex(Mutex::native, "JVM_RawMonitorCreate");
3473 }
3474 
3475 
3476 JNIEXPORT void JNICALL  JVM_RawMonitorDestroy(void *mon) {
3477   VM_Exit::block_if_vm_exited();
3478   JVMWrapper("JVM_RawMonitorDestroy");
3479   delete ((Mutex*) mon);
3480 }
3481 
3482 
3483 JNIEXPORT jint JNICALL JVM_RawMonitorEnter(void *mon) {
3484   VM_Exit::block_if_vm_exited();
3485   JVMWrapper("JVM_RawMonitorEnter");
3486   ((Mutex*) mon)->jvm_raw_lock();
3487   return 0;
3488 }
3489 
3490 
3491 JNIEXPORT void JNICALL JVM_RawMonitorExit(void *mon) {
3492   VM_Exit::block_if_vm_exited();
3493   JVMWrapper("JVM_RawMonitorExit");
3494   ((Mutex*) mon)->jvm_raw_unlock();
3495 }
3496 
3497 
3498 // Shared JNI/JVM entry points //////////////////////////////////////////////////////////////
3499 
3500 jclass find_class_from_class_loader(JNIEnv* env, Symbol* name, jboolean init,
3501                                     Handle loader, Handle protection_domain,
3502                                     jboolean throwError, TRAPS) {
3503   // Security Note:
3504   //   The Java level wrapper will perform the necessary security check allowing
3505   //   us to pass the NULL as the initiating class loader.  The VM is responsible for
3506   //   the checkPackageAccess relative to the initiating class loader via the
3507   //   protection_domain. The protection_domain is passed as NULL by the java code
3508   //   if there is no security manager in 3-arg Class.forName().
3509   Klass* klass = SystemDictionary::resolve_or_fail(name, loader, protection_domain, throwError != 0, CHECK_NULL);
3510 
3511   KlassHandle klass_handle(THREAD, klass);
3512   // Check if we should initialize the class
3513   if (init && klass_handle->oop_is_instance()) {
3514     klass_handle->initialize(CHECK_NULL);
3515   }
3516   return (jclass) JNIHandles::make_local(env, klass_handle->java_mirror());
3517 }
3518 
3519 
3520 // Method ///////////////////////////////////////////////////////////////////////////////////////////
3521 
3522 JVM_ENTRY(jobject, JVM_InvokeMethod(JNIEnv *env, jobject method, jobject obj, jobjectArray args0))
3523   JVMWrapper("JVM_InvokeMethod");
3524   Handle method_handle;
3525   if (thread->stack_available((address) &method_handle) >= JVMInvokeMethodSlack) {
3526     method_handle = Handle(THREAD, JNIHandles::resolve(method));
3527     Handle receiver(THREAD, JNIHandles::resolve(obj));
3528     objArrayHandle args(THREAD, objArrayOop(JNIHandles::resolve(args0)));
3529     oop result = Reflection::invoke_method(method_handle(), receiver, args, CHECK_NULL);
3530     jobject res = JNIHandles::make_local(env, result);
3531     if (JvmtiExport::should_post_vm_object_alloc()) {
3532       oop ret_type = java_lang_reflect_Method::return_type(method_handle());
3533       assert(ret_type != NULL, "sanity check: ret_type oop must not be NULL!");
3534       if (java_lang_Class::is_primitive(ret_type)) {
3535         // Only for primitive type vm allocates memory for java object.
3536         // See box() method.
3537         JvmtiExport::post_vm_object_alloc(JavaThread::current(), result);
3538       }
3539     }
3540     return res;
3541   } else {
3542     THROW_0(vmSymbols::java_lang_StackOverflowError());
3543   }
3544 JVM_END
3545 
3546 
3547 JVM_ENTRY(jobject, JVM_NewInstanceFromConstructor(JNIEnv *env, jobject c, jobjectArray args0))
3548   JVMWrapper("JVM_NewInstanceFromConstructor");
3549   oop constructor_mirror = JNIHandles::resolve(c);
3550   objArrayHandle args(THREAD, objArrayOop(JNIHandles::resolve(args0)));
3551   oop result = Reflection::invoke_constructor(constructor_mirror, args, CHECK_NULL);
3552   jobject res = JNIHandles::make_local(env, result);
3553   if (JvmtiExport::should_post_vm_object_alloc()) {
3554     JvmtiExport::post_vm_object_alloc(JavaThread::current(), result);
3555   }
3556   return res;
3557 JVM_END
3558 
3559 // Atomic ///////////////////////////////////////////////////////////////////////////////////////////
3560 
3561 JVM_LEAF(jboolean, JVM_SupportsCX8())
3562   JVMWrapper("JVM_SupportsCX8");
3563   return VM_Version::supports_cx8();
3564 JVM_END
3565 
3566 // DTrace ///////////////////////////////////////////////////////////////////
3567 
3568 JVM_ENTRY(jint, JVM_DTraceGetVersion(JNIEnv* env))
3569   JVMWrapper("JVM_DTraceGetVersion");
3570   return (jint)JVM_TRACING_DTRACE_VERSION;
3571 JVM_END
3572 
3573 JVM_ENTRY(jlong,JVM_DTraceActivate(
3574     JNIEnv* env, jint version, jstring module_name, jint providers_count,
3575     JVM_DTraceProvider* providers))
3576   JVMWrapper("JVM_DTraceActivate");
3577   return DTraceJSDT::activate(
3578     version, module_name, providers_count, providers, THREAD);
3579 JVM_END
3580 
3581 JVM_ENTRY(jboolean,JVM_DTraceIsProbeEnabled(JNIEnv* env, jmethodID method))
3582   JVMWrapper("JVM_DTraceIsProbeEnabled");
3583   return DTraceJSDT::is_probe_enabled(method);
3584 JVM_END
3585 
3586 JVM_ENTRY(void,JVM_DTraceDispose(JNIEnv* env, jlong handle))
3587   JVMWrapper("JVM_DTraceDispose");
3588   DTraceJSDT::dispose(handle);
3589 JVM_END
3590 
3591 JVM_ENTRY(jboolean,JVM_DTraceIsSupported(JNIEnv* env))
3592   JVMWrapper("JVM_DTraceIsSupported");
3593   return DTraceJSDT::is_supported();
3594 JVM_END
3595 
3596 // Returns an array of all live Thread objects (VM internal JavaThreads,
3597 // jvmti agent threads, and JNI attaching threads  are skipped)
3598 // See CR 6404306 regarding JNI attaching threads
3599 JVM_ENTRY(jobjectArray, JVM_GetAllThreads(JNIEnv *env, jclass dummy))
3600   ResourceMark rm(THREAD);
3601   ThreadsListEnumerator tle(THREAD, false, false);
3602   JvmtiVMObjectAllocEventCollector oam;
3603 
3604   int num_threads = tle.num_threads();
3605   objArrayOop r = oopFactory::new_objArray(SystemDictionary::Thread_klass(), num_threads, CHECK_NULL);
3606   objArrayHandle threads_ah(THREAD, r);
3607 
3608   for (int i = 0; i < num_threads; i++) {
3609     Handle h = tle.get_threadObj(i);
3610     threads_ah->obj_at_put(i, h());
3611   }
3612 
3613   return (jobjectArray) JNIHandles::make_local(env, threads_ah());
3614 JVM_END
3615 
3616 
3617 // Support for java.lang.Thread.getStackTrace() and getAllStackTraces() methods
3618 // Return StackTraceElement[][], each element is the stack trace of a thread in
3619 // the corresponding entry in the given threads array
3620 JVM_ENTRY(jobjectArray, JVM_DumpThreads(JNIEnv *env, jclass threadClass, jobjectArray threads))
3621   JVMWrapper("JVM_DumpThreads");
3622   JvmtiVMObjectAllocEventCollector oam;
3623 
3624   // Check if threads is null
3625   if (threads == NULL) {
3626     THROW_(vmSymbols::java_lang_NullPointerException(), 0);
3627   }
3628 
3629   objArrayOop a = objArrayOop(JNIHandles::resolve_non_null(threads));
3630   objArrayHandle ah(THREAD, a);
3631   int num_threads = ah->length();
3632   // check if threads is non-empty array
3633   if (num_threads == 0) {
3634     THROW_(vmSymbols::java_lang_IllegalArgumentException(), 0);
3635   }
3636 
3637   // check if threads is not an array of objects of Thread class
3638   Klass* k = ObjArrayKlass::cast(ah->klass())->element_klass();
3639   if (k != SystemDictionary::Thread_klass()) {
3640     THROW_(vmSymbols::java_lang_IllegalArgumentException(), 0);
3641   }
3642 
3643   ResourceMark rm(THREAD);
3644 
3645   GrowableArray<instanceHandle>* thread_handle_array = new GrowableArray<instanceHandle>(num_threads);
3646   for (int i = 0; i < num_threads; i++) {
3647     oop thread_obj = ah->obj_at(i);
3648     instanceHandle h(THREAD, (instanceOop) thread_obj);
3649     thread_handle_array->append(h);
3650   }
3651 
3652   Handle stacktraces = ThreadService::dump_stack_traces(thread_handle_array, num_threads, CHECK_NULL);
3653   return (jobjectArray)JNIHandles::make_local(env, stacktraces());
3654 
3655 JVM_END
3656 
3657 // JVM monitoring and management support
3658 JVM_ENTRY_NO_ENV(void*, JVM_GetManagement(jint version))
3659   return Management::get_jmm_interface(version);
3660 JVM_END
3661 
3662 // com.sun.tools.attach.VirtualMachine agent properties support
3663 //
3664 // Initialize the agent properties with the properties maintained in the VM
3665 JVM_ENTRY(jobject, JVM_InitAgentProperties(JNIEnv *env, jobject properties))
3666   JVMWrapper("JVM_InitAgentProperties");
3667   ResourceMark rm;
3668 
3669   Handle props(THREAD, JNIHandles::resolve_non_null(properties));
3670 
3671   PUTPROP(props, "sun.java.command", Arguments::java_command());
3672   PUTPROP(props, "sun.jvm.flags", Arguments::jvm_flags());
3673   PUTPROP(props, "sun.jvm.args", Arguments::jvm_args());
3674   return properties;
3675 JVM_END
3676 
3677 JVM_ENTRY(jobjectArray, JVM_GetEnclosingMethodInfo(JNIEnv *env, jclass ofClass))
3678 {
3679   JVMWrapper("JVM_GetEnclosingMethodInfo");
3680   JvmtiVMObjectAllocEventCollector oam;
3681 
3682   if (ofClass == NULL) {
3683     return NULL;
3684   }
3685   Handle mirror(THREAD, JNIHandles::resolve_non_null(ofClass));
3686   // Special handling for primitive objects
3687   if (java_lang_Class::is_primitive(mirror())) {
3688     return NULL;
3689   }
3690   Klass* k = java_lang_Class::as_Klass(mirror());
3691   if (!k->oop_is_instance()) {
3692     return NULL;
3693   }
3694   instanceKlassHandle ik_h(THREAD, k);
3695   int encl_method_class_idx = ik_h->enclosing_method_class_index();
3696   if (encl_method_class_idx == 0) {
3697     return NULL;
3698   }
3699   objArrayOop dest_o = oopFactory::new_objArray(SystemDictionary::Object_klass(), 3, CHECK_NULL);
3700   objArrayHandle dest(THREAD, dest_o);
3701   Klass* enc_k = ik_h->constants()->klass_at(encl_method_class_idx, CHECK_NULL);
3702   dest->obj_at_put(0, enc_k->java_mirror());
3703   int encl_method_method_idx = ik_h->enclosing_method_method_index();
3704   if (encl_method_method_idx != 0) {
3705     Symbol* sym = ik_h->constants()->symbol_at(
3706                         extract_low_short_from_int(
3707                           ik_h->constants()->name_and_type_at(encl_method_method_idx)));
3708     Handle str = java_lang_String::create_from_symbol(sym, CHECK_NULL);
3709     dest->obj_at_put(1, str());
3710     sym = ik_h->constants()->symbol_at(
3711               extract_high_short_from_int(
3712                 ik_h->constants()->name_and_type_at(encl_method_method_idx)));
3713     str = java_lang_String::create_from_symbol(sym, CHECK_NULL);
3714     dest->obj_at_put(2, str());
3715   }
3716   return (jobjectArray) JNIHandles::make_local(dest());
3717 }
3718 JVM_END
3719 
3720 JVM_ENTRY(void, JVM_GetVersionInfo(JNIEnv* env, jvm_version_info* info, size_t info_size))
3721 {
3722   memset(info, 0, info_size);
3723 
3724   info->jvm_version = Abstract_VM_Version::jvm_version();
3725   info->update_version = 0;          /* 0 in HotSpot Express VM */
3726   info->special_update_version = 0;  /* 0 in HotSpot Express VM */
3727 
3728   // when we add a new capability in the jvm_version_info struct, we should also
3729   // consider to expose this new capability in the sun.rt.jvmCapabilities jvmstat
3730   // counter defined in runtimeService.cpp.
3731   info->is_attachable = AttachListener::is_attach_supported();
3732 }
3733 JVM_END