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