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