Path: blob/jdk8u272-b10-aarch32-20201026/hotspot/src/share/vm/prims/jvm.cpp
48773 views
/*1* Copyright (c) 1997, 2020, Oracle and/or its affiliates. All rights reserved2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*22*/2324#include "precompiled.hpp"25#include "classfile/classLoader.hpp"26#include "classfile/classLoaderData.inline.hpp"27#include "classfile/classLoaderExt.hpp"28#include "classfile/javaAssertions.hpp"29#include "classfile/javaClasses.hpp"30#include "classfile/symbolTable.hpp"31#include "classfile/systemDictionary.hpp"32#if INCLUDE_CDS33#include "classfile/sharedClassUtil.hpp"34#include "classfile/systemDictionaryShared.hpp"35#endif36#include "classfile/vmSymbols.hpp"37#include "gc_interface/collectedHeap.inline.hpp"38#include "interpreter/bytecode.hpp"39#include "jfr/jfrEvents.hpp"40#include "memory/oopFactory.hpp"41#include "memory/referenceType.hpp"42#include "memory/universe.inline.hpp"43#include "oops/fieldStreams.hpp"44#include "oops/instanceKlass.hpp"45#include "oops/objArrayKlass.hpp"46#include "oops/method.hpp"47#include "prims/jvm.h"48#include "prims/jvm_misc.hpp"49#include "prims/jvmtiExport.hpp"50#include "prims/jvmtiThreadState.hpp"51#include "prims/nativeLookup.hpp"52#include "prims/privilegedStack.hpp"53#include "runtime/arguments.hpp"54#include "runtime/dtraceJSDT.hpp"55#include "runtime/handles.inline.hpp"56#include "runtime/init.hpp"57#include "runtime/interfaceSupport.hpp"58#include "runtime/java.hpp"59#include "runtime/javaCalls.hpp"60#include "runtime/jfieldIDWorkaround.hpp"61#include "runtime/orderAccess.inline.hpp"62#include "runtime/os.hpp"63#include "runtime/perfData.hpp"64#include "runtime/reflection.hpp"65#include "runtime/vframe.hpp"66#include "runtime/vm_operations.hpp"67#include "services/attachListener.hpp"68#include "services/management.hpp"69#include "services/threadService.hpp"70#include "utilities/copy.hpp"71#include "utilities/defaultStream.hpp"72#include "utilities/dtrace.hpp"73#include "utilities/events.hpp"74#include "utilities/histogram.hpp"75#include "utilities/top.hpp"76#include "utilities/utf8.hpp"77#ifdef TARGET_OS_FAMILY_linux78# include "jvm_linux.h"79#endif80#ifdef TARGET_OS_FAMILY_solaris81# include "jvm_solaris.h"82#endif83#ifdef TARGET_OS_FAMILY_windows84# include "jvm_windows.h"85#endif86#ifdef TARGET_OS_FAMILY_aix87# include "jvm_aix.h"88#endif89#ifdef TARGET_OS_FAMILY_bsd90# include "jvm_bsd.h"91#endif9293#if INCLUDE_ALL_GCS94#include "gc_implementation/g1/g1SATBCardTableModRefBS.hpp"95#endif // INCLUDE_ALL_GCS9697#include <errno.h>9899#ifndef USDT2100HS_DTRACE_PROBE_DECL1(hotspot, thread__sleep__begin, long long);101HS_DTRACE_PROBE_DECL1(hotspot, thread__sleep__end, int);102HS_DTRACE_PROBE_DECL0(hotspot, thread__yield);103#endif /* !USDT2 */104105/*106NOTE about use of any ctor or function call that can trigger a safepoint/GC:107such ctors and calls MUST NOT come between an oop declaration/init and its108usage because if objects are move this may cause various memory stomps, bus109errors and segfaults. Here is a cookbook for causing so called "naked oop110failures":111112JVM_ENTRY(jobjectArray, JVM_GetClassDeclaredFields<etc> {113JVMWrapper("JVM_GetClassDeclaredFields");114115// Object address to be held directly in mirror & not visible to GC116oop mirror = JNIHandles::resolve_non_null(ofClass);117118// If this ctor can hit a safepoint, moving objects around, then119ComplexConstructor foo;120121// Boom! mirror may point to JUNK instead of the intended object122(some dereference of mirror)123124// Here's another call that may block for GC, making mirror stale125MutexLocker ml(some_lock);126127// And here's an initializer that can result in a stale oop128// all in one step.129oop o = call_that_can_throw_exception(TRAPS);130131132The solution is to keep the oop declaration BELOW the ctor or function133call that might cause a GC, do another resolve to reassign the oop, or134consider use of a Handle instead of an oop so there is immunity from object135motion. But note that the "QUICK" entries below do not have a handlemark136and thus can only support use of handles passed in.137*/138139static void trace_class_resolution_impl(Klass* to_class, TRAPS) {140ResourceMark rm;141int line_number = -1;142const char * source_file = NULL;143const char * trace = "explicit";144InstanceKlass* caller = NULL;145JavaThread* jthread = JavaThread::current();146if (jthread->has_last_Java_frame()) {147vframeStream vfst(jthread);148149// scan up the stack skipping ClassLoader, AccessController and PrivilegedAction frames150TempNewSymbol access_controller = SymbolTable::new_symbol("java/security/AccessController", CHECK);151Klass* access_controller_klass = SystemDictionary::resolve_or_fail(access_controller, false, CHECK);152TempNewSymbol privileged_action = SymbolTable::new_symbol("java/security/PrivilegedAction", CHECK);153Klass* privileged_action_klass = SystemDictionary::resolve_or_fail(privileged_action, false, CHECK);154155Method* last_caller = NULL;156157while (!vfst.at_end()) {158Method* m = vfst.method();159if (!vfst.method()->method_holder()->is_subclass_of(SystemDictionary::ClassLoader_klass())&&160!vfst.method()->method_holder()->is_subclass_of(access_controller_klass) &&161!vfst.method()->method_holder()->is_subclass_of(privileged_action_klass)) {162break;163}164last_caller = m;165vfst.next();166}167// if this is called from Class.forName0 and that is called from Class.forName,168// then print the caller of Class.forName. If this is Class.loadClass, then print169// that caller, otherwise keep quiet since this should be picked up elsewhere.170bool found_it = false;171if (!vfst.at_end() &&172vfst.method()->method_holder()->name() == vmSymbols::java_lang_Class() &&173vfst.method()->name() == vmSymbols::forName0_name()) {174vfst.next();175if (!vfst.at_end() &&176vfst.method()->method_holder()->name() == vmSymbols::java_lang_Class() &&177vfst.method()->name() == vmSymbols::forName_name()) {178vfst.next();179found_it = true;180}181} else if (last_caller != NULL &&182last_caller->method_holder()->name() ==183vmSymbols::java_lang_ClassLoader() &&184(last_caller->name() == vmSymbols::loadClassInternal_name() ||185last_caller->name() == vmSymbols::loadClass_name())) {186found_it = true;187} else if (!vfst.at_end()) {188if (vfst.method()->is_native()) {189// JNI call190found_it = true;191}192}193if (found_it && !vfst.at_end()) {194// found the caller195caller = vfst.method()->method_holder();196line_number = vfst.method()->line_number_from_bci(vfst.bci());197if (line_number == -1) {198// show method name if it's a native method199trace = vfst.method()->name_and_sig_as_C_string();200}201Symbol* s = caller->source_file_name();202if (s != NULL) {203source_file = s->as_C_string();204}205}206}207if (caller != NULL) {208if (to_class != caller) {209const char * from = caller->external_name();210const char * to = to_class->external_name();211// print in a single call to reduce interleaving between threads212if (source_file != NULL) {213tty->print("RESOLVE %s %s %s:%d (%s)\n", from, to, source_file, line_number, trace);214} else {215tty->print("RESOLVE %s %s (%s)\n", from, to, trace);216}217}218}219}220221void trace_class_resolution(Klass* to_class) {222EXCEPTION_MARK;223trace_class_resolution_impl(to_class, THREAD);224if (HAS_PENDING_EXCEPTION) {225CLEAR_PENDING_EXCEPTION;226}227}228229// Wrapper to trace JVM functions230231#ifdef ASSERT232class JVMTraceWrapper : public StackObj {233public:234JVMTraceWrapper(const char* format, ...) ATTRIBUTE_PRINTF(2, 3) {235if (TraceJVMCalls) {236va_list ap;237va_start(ap, format);238tty->print("JVM ");239tty->vprint_cr(format, ap);240va_end(ap);241}242}243};244245Histogram* JVMHistogram;246volatile jint JVMHistogram_lock = 0;247248class JVMHistogramElement : public HistogramElement {249public:250JVMHistogramElement(const char* name);251};252253JVMHistogramElement::JVMHistogramElement(const char* elementName) {254_name = elementName;255uintx count = 0;256257while (Atomic::cmpxchg(1, &JVMHistogram_lock, 0) != 0) {258while (OrderAccess::load_acquire(&JVMHistogram_lock) != 0) {259count +=1;260if ( (WarnOnStalledSpinLock > 0)261&& (count % WarnOnStalledSpinLock == 0)) {262warning("JVMHistogram_lock seems to be stalled");263}264}265}266267if(JVMHistogram == NULL)268JVMHistogram = new Histogram("JVM Call Counts",100);269270JVMHistogram->add_element(this);271Atomic::dec(&JVMHistogram_lock);272}273274#define JVMCountWrapper(arg) \275static JVMHistogramElement* e = new JVMHistogramElement(arg); \276if (e != NULL) e->increment_count(); // Due to bug in VC++, we need a NULL check here eventhough it should never happen!277278#define JVMWrapper(arg1) JVMCountWrapper(arg1); JVMTraceWrapper(arg1)279#define JVMWrapper2(arg1, arg2) JVMCountWrapper(arg1); JVMTraceWrapper(arg1, arg2)280#define JVMWrapper3(arg1, arg2, arg3) JVMCountWrapper(arg1); JVMTraceWrapper(arg1, arg2, arg3)281#define JVMWrapper4(arg1, arg2, arg3, arg4) JVMCountWrapper(arg1); JVMTraceWrapper(arg1, arg2, arg3, arg4)282#else283#define JVMWrapper(arg1)284#define JVMWrapper2(arg1, arg2)285#define JVMWrapper3(arg1, arg2, arg3)286#define JVMWrapper4(arg1, arg2, arg3, arg4)287#endif288289290// Interface version /////////////////////////////////////////////////////////////////////291292293JVM_LEAF(jint, JVM_GetInterfaceVersion())294return JVM_INTERFACE_VERSION;295JVM_END296297298// java.lang.System //////////////////////////////////////////////////////////////////////299300301JVM_LEAF(jlong, JVM_CurrentTimeMillis(JNIEnv *env, jclass ignored))302JVMWrapper("JVM_CurrentTimeMillis");303return os::javaTimeMillis();304JVM_END305306JVM_LEAF(jlong, JVM_NanoTime(JNIEnv *env, jclass ignored))307JVMWrapper("JVM_NanoTime");308return os::javaTimeNanos();309JVM_END310311312JVM_ENTRY(void, JVM_ArrayCopy(JNIEnv *env, jclass ignored, jobject src, jint src_pos,313jobject dst, jint dst_pos, jint length))314JVMWrapper("JVM_ArrayCopy");315// Check if we have null pointers316if (src == NULL || dst == NULL) {317THROW(vmSymbols::java_lang_NullPointerException());318}319arrayOop s = arrayOop(JNIHandles::resolve_non_null(src));320arrayOop d = arrayOop(JNIHandles::resolve_non_null(dst));321assert(s->is_oop(), "JVM_ArrayCopy: src not an oop");322assert(d->is_oop(), "JVM_ArrayCopy: dst not an oop");323// Do copy324s->klass()->copy_array(s, src_pos, d, dst_pos, length, thread);325JVM_END326327328static void set_property(Handle props, const char* key, const char* value, TRAPS) {329JavaValue r(T_OBJECT);330// public synchronized Object put(Object key, Object value);331HandleMark hm(THREAD);332Handle key_str = java_lang_String::create_from_platform_dependent_str(key, CHECK);333Handle value_str = java_lang_String::create_from_platform_dependent_str((value != NULL ? value : ""), CHECK);334JavaCalls::call_virtual(&r,335props,336KlassHandle(THREAD, SystemDictionary::Properties_klass()),337vmSymbols::put_name(),338vmSymbols::object_object_object_signature(),339key_str,340value_str,341THREAD);342}343344345#define PUTPROP(props, name, value) set_property((props), (name), (value), CHECK_(properties));346347348JVM_ENTRY(jobject, JVM_InitProperties(JNIEnv *env, jobject properties))349JVMWrapper("JVM_InitProperties");350ResourceMark rm;351352Handle props(THREAD, JNIHandles::resolve_non_null(properties));353354// System property list includes both user set via -D option and355// jvm system specific properties.356for (SystemProperty* p = Arguments::system_properties(); p != NULL; p = p->next()) {357PUTPROP(props, p->key(), p->value());358}359360// Convert the -XX:MaxDirectMemorySize= command line flag361// to the sun.nio.MaxDirectMemorySize property.362// Do this after setting user properties to prevent people363// from setting the value with a -D option, as requested.364{365if (FLAG_IS_DEFAULT(MaxDirectMemorySize)) {366PUTPROP(props, "sun.nio.MaxDirectMemorySize", "-1");367} else {368char as_chars[256];369jio_snprintf(as_chars, sizeof(as_chars), UINTX_FORMAT, MaxDirectMemorySize);370PUTPROP(props, "sun.nio.MaxDirectMemorySize", as_chars);371}372}373374// JVM monitoring and management support375// Add the sun.management.compiler property for the compiler's name376{377#undef CSIZE378#if defined(_LP64) || defined(_WIN64)379#define CSIZE "64-Bit "380#else381#define CSIZE382#endif // 64bit383384#ifdef TIERED385const char* compiler_name = "HotSpot " CSIZE "Tiered Compilers";386#else387#if defined(COMPILER1)388const char* compiler_name = "HotSpot " CSIZE "Client Compiler";389#elif defined(COMPILER2)390const char* compiler_name = "HotSpot " CSIZE "Server Compiler";391#else392const char* compiler_name = "";393#endif // compilers394#endif // TIERED395396if (*compiler_name != '\0' &&397(Arguments::mode() != Arguments::_int)) {398PUTPROP(props, "sun.management.compiler", compiler_name);399}400}401402const char* enableSharedLookupCache = "false";403#if INCLUDE_CDS404if (ClassLoaderExt::is_lookup_cache_enabled()) {405enableSharedLookupCache = "true";406}407#endif408PUTPROP(props, "sun.cds.enableSharedLookupCache", enableSharedLookupCache);409410return properties;411JVM_END412413414/*415* Return the temporary directory that the VM uses for the attach416* and perf data files.417*418* It is important that this directory is well-known and the419* same for all VM instances. It cannot be affected by configuration420* variables such as java.io.tmpdir.421*/422JVM_ENTRY(jstring, JVM_GetTemporaryDirectory(JNIEnv *env))423JVMWrapper("JVM_GetTemporaryDirectory");424HandleMark hm(THREAD);425const char* temp_dir = os::get_temp_directory();426Handle h = java_lang_String::create_from_platform_dependent_str(temp_dir, CHECK_NULL);427return (jstring) JNIHandles::make_local(env, h());428JVM_END429430431// java.lang.Runtime /////////////////////////////////////////////////////////////////////////432433extern volatile jint vm_created;434435JVM_ENTRY_NO_ENV(void, JVM_Exit(jint code))436if (vm_created != 0 && (code == 0)) {437// The VM is about to exit. We call back into Java to check whether finalizers should be run438Universe::run_finalizers_on_exit();439}440before_exit(thread);441vm_exit(code);442JVM_END443444445JVM_ENTRY_NO_ENV(void, JVM_BeforeHalt())446JVMWrapper("JVM_BeforeHalt");447EventShutdown event;448if (event.should_commit()) {449event.set_reason("Shutdown requested from Java");450event.commit();451}452JVM_END453454455JVM_ENTRY_NO_ENV(void, JVM_Halt(jint code))456before_exit(thread);457vm_exit(code);458JVM_END459460461JVM_LEAF(void, JVM_OnExit(void (*func)(void)))462register_on_exit_function(func);463JVM_END464465466JVM_ENTRY_NO_ENV(void, JVM_GC(void))467JVMWrapper("JVM_GC");468if (!DisableExplicitGC) {469Universe::heap()->collect(GCCause::_java_lang_system_gc);470}471JVM_END472473474JVM_LEAF(jlong, JVM_MaxObjectInspectionAge(void))475JVMWrapper("JVM_MaxObjectInspectionAge");476return Universe::heap()->millis_since_last_gc();477JVM_END478479480JVM_LEAF(void, JVM_TraceInstructions(jboolean on))481if (PrintJVMWarnings) warning("JVM_TraceInstructions not supported");482JVM_END483484485JVM_LEAF(void, JVM_TraceMethodCalls(jboolean on))486if (PrintJVMWarnings) warning("JVM_TraceMethodCalls not supported");487JVM_END488489static inline jlong convert_size_t_to_jlong(size_t val) {490// In the 64-bit vm, a size_t can overflow a jlong (which is signed).491NOT_LP64 (return (jlong)val;)492LP64_ONLY(return (jlong)MIN2(val, (size_t)max_jlong);)493}494495JVM_ENTRY_NO_ENV(jlong, JVM_TotalMemory(void))496JVMWrapper("JVM_TotalMemory");497size_t n = Universe::heap()->capacity();498return convert_size_t_to_jlong(n);499JVM_END500501502JVM_ENTRY_NO_ENV(jlong, JVM_FreeMemory(void))503JVMWrapper("JVM_FreeMemory");504CollectedHeap* ch = Universe::heap();505size_t n;506{507MutexLocker x(Heap_lock);508n = ch->capacity() - ch->used();509}510return convert_size_t_to_jlong(n);511JVM_END512513514JVM_ENTRY_NO_ENV(jlong, JVM_MaxMemory(void))515JVMWrapper("JVM_MaxMemory");516size_t n = Universe::heap()->max_capacity();517return convert_size_t_to_jlong(n);518JVM_END519520521JVM_ENTRY_NO_ENV(jint, JVM_ActiveProcessorCount(void))522JVMWrapper("JVM_ActiveProcessorCount");523return os::active_processor_count();524JVM_END525526527JVM_ENTRY_NO_ENV(jboolean, JVM_IsUseContainerSupport(void))528JVMWrapper("JVM_IsUseContainerSupport");529#ifdef TARGET_OS_FAMILY_linux530if (UseContainerSupport) {531return JNI_TRUE;532}533#endif534return JNI_FALSE;535JVM_END536537538539// java.lang.Throwable //////////////////////////////////////////////////////540541542JVM_ENTRY(void, JVM_FillInStackTrace(JNIEnv *env, jobject receiver))543JVMWrapper("JVM_FillInStackTrace");544Handle exception(thread, JNIHandles::resolve_non_null(receiver));545java_lang_Throwable::fill_in_stack_trace(exception);546JVM_END547548549JVM_ENTRY(jint, JVM_GetStackTraceDepth(JNIEnv *env, jobject throwable))550JVMWrapper("JVM_GetStackTraceDepth");551oop exception = JNIHandles::resolve(throwable);552return java_lang_Throwable::get_stack_trace_depth(exception, THREAD);553JVM_END554555556JVM_ENTRY(jobject, JVM_GetStackTraceElement(JNIEnv *env, jobject throwable, jint index))557JVMWrapper("JVM_GetStackTraceElement");558JvmtiVMObjectAllocEventCollector oam; // This ctor (throughout this module) may trigger a safepoint/GC559oop exception = JNIHandles::resolve(throwable);560oop element = java_lang_Throwable::get_stack_trace_element(exception, index, CHECK_NULL);561return JNIHandles::make_local(env, element);562JVM_END563564565// java.lang.Object ///////////////////////////////////////////////566567568JVM_ENTRY(jint, JVM_IHashCode(JNIEnv* env, jobject handle))569JVMWrapper("JVM_IHashCode");570// as implemented in the classic virtual machine; return 0 if object is NULL571return handle == NULL ? 0 : ObjectSynchronizer::FastHashCode (THREAD, JNIHandles::resolve_non_null(handle)) ;572JVM_END573574575JVM_ENTRY(void, JVM_MonitorWait(JNIEnv* env, jobject handle, jlong ms))576JVMWrapper("JVM_MonitorWait");577Handle obj(THREAD, JNIHandles::resolve_non_null(handle));578JavaThreadInObjectWaitState jtiows(thread, ms != 0);579if (JvmtiExport::should_post_monitor_wait()) {580JvmtiExport::post_monitor_wait((JavaThread *)THREAD, (oop)obj(), ms);581582// The current thread already owns the monitor and it has not yet583// been added to the wait queue so the current thread cannot be584// made the successor. This means that the JVMTI_EVENT_MONITOR_WAIT585// event handler cannot accidentally consume an unpark() meant for586// the ParkEvent associated with this ObjectMonitor.587}588ObjectSynchronizer::wait(obj, ms, CHECK);589JVM_END590591592JVM_ENTRY(void, JVM_MonitorNotify(JNIEnv* env, jobject handle))593JVMWrapper("JVM_MonitorNotify");594Handle obj(THREAD, JNIHandles::resolve_non_null(handle));595ObjectSynchronizer::notify(obj, CHECK);596JVM_END597598599JVM_ENTRY(void, JVM_MonitorNotifyAll(JNIEnv* env, jobject handle))600JVMWrapper("JVM_MonitorNotifyAll");601Handle obj(THREAD, JNIHandles::resolve_non_null(handle));602ObjectSynchronizer::notifyall(obj, CHECK);603JVM_END604605606static void fixup_cloned_reference(ReferenceType ref_type, oop src, oop clone) {607// If G1 is enabled then we need to register a non-null referent608// with the SATB barrier.609#if INCLUDE_ALL_GCS610if (UseG1GC) {611oop referent = java_lang_ref_Reference::referent(clone);612if (referent != NULL) {613G1SATBCardTableModRefBS::enqueue(referent);614}615}616#endif // INCLUDE_ALL_GCS617if ((java_lang_ref_Reference::next(clone) != NULL) ||618(java_lang_ref_Reference::queue(clone) == java_lang_ref_ReferenceQueue::ENQUEUED_queue())) {619// If the source has been enqueued or is being enqueued, don't620// register the clone with a queue.621java_lang_ref_Reference::set_queue(clone, java_lang_ref_ReferenceQueue::NULL_queue());622}623// discovered and next are list links; the clone is not in those lists.624java_lang_ref_Reference::set_discovered(clone, NULL);625java_lang_ref_Reference::set_next(clone, NULL);626}627628JVM_ENTRY(jobject, JVM_Clone(JNIEnv* env, jobject handle))629JVMWrapper("JVM_Clone");630Handle obj(THREAD, JNIHandles::resolve_non_null(handle));631const KlassHandle klass (THREAD, obj->klass());632JvmtiVMObjectAllocEventCollector oam;633634#ifdef ASSERT635// Just checking that the cloneable flag is set correct636if (obj->is_array()) {637guarantee(klass->is_cloneable(), "all arrays are cloneable");638} else {639guarantee(obj->is_instance(), "should be instanceOop");640bool cloneable = klass->is_subtype_of(SystemDictionary::Cloneable_klass());641guarantee(cloneable == klass->is_cloneable(), "incorrect cloneable flag");642}643#endif644645// Check if class of obj supports the Cloneable interface.646// All arrays are considered to be cloneable (See JLS 20.1.5)647if (!klass->is_cloneable()) {648ResourceMark rm(THREAD);649THROW_MSG_0(vmSymbols::java_lang_CloneNotSupportedException(), klass->external_name());650}651652// Make shallow object copy653ReferenceType ref_type = REF_NONE;654const int size = obj->size();655oop new_obj_oop = NULL;656if (obj->is_array()) {657const int length = ((arrayOop)obj())->length();658new_obj_oop = CollectedHeap::array_allocate(klass, size, length, CHECK_NULL);659} else {660ref_type = InstanceKlass::cast(klass())->reference_type();661assert((ref_type == REF_NONE) ==662!klass->is_subclass_of(SystemDictionary::Reference_klass()),663"invariant");664new_obj_oop = CollectedHeap::obj_allocate(klass, size, CHECK_NULL);665}666667// 4839641 (4840070): We must do an oop-atomic copy, because if another thread668// is modifying a reference field in the clonee, a non-oop-atomic copy might669// be suspended in the middle of copying the pointer and end up with parts670// of two different pointers in the field. Subsequent dereferences will crash.671// 4846409: an oop-copy of objects with long or double fields or arrays of same672// won't copy the longs/doubles atomically in 32-bit vm's, so we copy jlongs instead673// of oops. We know objects are aligned on a minimum of an jlong boundary.674// The same is true of StubRoutines::object_copy and the various oop_copy675// variants, and of the code generated by the inline_native_clone intrinsic.676assert(MinObjAlignmentInBytes >= BytesPerLong, "objects misaligned");677Copy::conjoint_jlongs_atomic((jlong*)obj(), (jlong*)new_obj_oop,678(size_t)align_object_size(size) / HeapWordsPerLong);679// Clear the header680new_obj_oop->init_mark();681682// Store check (mark entire object and let gc sort it out)683BarrierSet* bs = Universe::heap()->barrier_set();684assert(bs->has_write_region_opt(), "Barrier set does not have write_region");685bs->write_region(MemRegion((HeapWord*)new_obj_oop, size));686687// If cloning a Reference, set Reference fields to a safe state.688// Fixup must be completed before any safepoint.689if (ref_type != REF_NONE) {690fixup_cloned_reference(ref_type, obj(), new_obj_oop);691}692693Handle new_obj(THREAD, new_obj_oop);694// Special handling for MemberNames. Since they contain Method* metadata, they695// must be registered so that RedefineClasses can fix metadata contained in them.696if (java_lang_invoke_MemberName::is_instance(new_obj()) &&697java_lang_invoke_MemberName::is_method(new_obj())) {698Method* method = (Method*)java_lang_invoke_MemberName::vmtarget(new_obj());699// MemberName may be unresolved, so doesn't need registration until resolved.700if (method != NULL) {701methodHandle m(THREAD, method);702// This can safepoint and redefine method, so need both new_obj and method703// in a handle, for two different reasons. new_obj can move, method can be704// deleted if nothing is using it on the stack.705m->method_holder()->add_member_name(new_obj(), false);706}707}708709// Caution: this involves a java upcall, so the clone should be710// "gc-robust" by this stage.711if (klass->has_finalizer()) {712assert(obj->is_instance(), "should be instanceOop");713new_obj_oop = InstanceKlass::register_finalizer(instanceOop(new_obj()), CHECK_NULL);714new_obj = Handle(THREAD, new_obj_oop);715}716717return JNIHandles::make_local(env, new_obj());718JVM_END719720// java.lang.Compiler ////////////////////////////////////////////////////721722// The initial cuts of the HotSpot VM will not support JITs, and all existing723// JITs would need extensive changes to work with HotSpot. The JIT-related JVM724// functions are all silently ignored unless JVM warnings are printed.725726JVM_LEAF(void, JVM_InitializeCompiler (JNIEnv *env, jclass compCls))727if (PrintJVMWarnings) warning("JVM_InitializeCompiler not supported");728JVM_END729730731JVM_LEAF(jboolean, JVM_IsSilentCompiler(JNIEnv *env, jclass compCls))732if (PrintJVMWarnings) warning("JVM_IsSilentCompiler not supported");733return JNI_FALSE;734JVM_END735736737JVM_LEAF(jboolean, JVM_CompileClass(JNIEnv *env, jclass compCls, jclass cls))738if (PrintJVMWarnings) warning("JVM_CompileClass not supported");739return JNI_FALSE;740JVM_END741742743JVM_LEAF(jboolean, JVM_CompileClasses(JNIEnv *env, jclass cls, jstring jname))744if (PrintJVMWarnings) warning("JVM_CompileClasses not supported");745return JNI_FALSE;746JVM_END747748749JVM_LEAF(jobject, JVM_CompilerCommand(JNIEnv *env, jclass compCls, jobject arg))750if (PrintJVMWarnings) warning("JVM_CompilerCommand not supported");751return NULL;752JVM_END753754755JVM_LEAF(void, JVM_EnableCompiler(JNIEnv *env, jclass compCls))756if (PrintJVMWarnings) warning("JVM_EnableCompiler not supported");757JVM_END758759760JVM_LEAF(void, JVM_DisableCompiler(JNIEnv *env, jclass compCls))761if (PrintJVMWarnings) warning("JVM_DisableCompiler not supported");762JVM_END763764765766// Error message support //////////////////////////////////////////////////////767768JVM_LEAF(jint, JVM_GetLastErrorString(char *buf, int len))769JVMWrapper("JVM_GetLastErrorString");770return (jint)os::lasterror(buf, len);771JVM_END772773774// java.io.File ///////////////////////////////////////////////////////////////775776JVM_LEAF(char*, JVM_NativePath(char* path))777JVMWrapper2("JVM_NativePath (%s)", path);778return os::native_path(path);779JVM_END780781782// java.nio.Bits ///////////////////////////////////////////////////////////////783784#define MAX_OBJECT_SIZE \785( arrayOopDesc::header_size(T_DOUBLE) * HeapWordSize \786+ ((julong)max_jint * sizeof(double)) )787788static inline jlong field_offset_to_byte_offset(jlong field_offset) {789return field_offset;790}791792static inline void assert_field_offset_sane(oop p, jlong field_offset) {793#ifdef ASSERT794jlong byte_offset = field_offset_to_byte_offset(field_offset);795796if (p != NULL) {797assert(byte_offset >= 0 && byte_offset <= (jlong)MAX_OBJECT_SIZE, "sane offset");798if (byte_offset == (jint)byte_offset) {799void* ptr_plus_disp = (address)p + byte_offset;800assert((void*)p->obj_field_addr<oop>((jint)byte_offset) == ptr_plus_disp,801"raw [ptr+disp] must be consistent with oop::field_base");802}803jlong p_size = HeapWordSize * (jlong)(p->size());804assert(byte_offset < p_size, err_msg("Unsafe access: offset " INT64_FORMAT805" > object's size " INT64_FORMAT,806(int64_t)byte_offset, (int64_t)p_size));807}808#endif809}810811static inline void* index_oop_from_field_offset_long(oop p, jlong field_offset) {812assert_field_offset_sane(p, field_offset);813jlong byte_offset = field_offset_to_byte_offset(field_offset);814815if (sizeof(char*) == sizeof(jint)) { // (this constant folds!)816return (address)p + (jint) byte_offset;817} else {818return (address)p + byte_offset;819}820}821822// This function is a leaf since if the source and destination are both in native memory823// the copy may potentially be very large, and we don't want to disable GC if we can avoid it.824// If either source or destination (or both) are on the heap, the function will enter VM using825// JVM_ENTRY_FROM_LEAF826JVM_LEAF(void, JVM_CopySwapMemory(JNIEnv *env, jobject srcObj, jlong srcOffset,827jobject dstObj, jlong dstOffset, jlong size,828jlong elemSize)) {829830size_t sz = (size_t)size;831size_t esz = (size_t)elemSize;832833if (srcObj == NULL && dstObj == NULL) {834// Both src & dst are in native memory835address src = (address)srcOffset;836address dst = (address)dstOffset;837838Copy::conjoint_swap(src, dst, sz, esz);839} else {840// At least one of src/dst are on heap, transition to VM to access raw pointers841842JVM_ENTRY_FROM_LEAF(env, void, JVM_CopySwapMemory) {843oop srcp = JNIHandles::resolve(srcObj);844oop dstp = JNIHandles::resolve(dstObj);845846address src = (address)index_oop_from_field_offset_long(srcp, srcOffset);847address dst = (address)index_oop_from_field_offset_long(dstp, dstOffset);848849Copy::conjoint_swap(src, dst, sz, esz);850} JVM_END851}852} JVM_END853854855// Misc. class handling ///////////////////////////////////////////////////////////856857858JVM_ENTRY(jclass, JVM_GetCallerClass(JNIEnv* env, int depth))859JVMWrapper("JVM_GetCallerClass");860861// Pre-JDK 8 and early builds of JDK 8 don't have a CallerSensitive annotation; or862// sun.reflect.Reflection.getCallerClass with a depth parameter is provided863// temporarily for existing code to use until a replacement API is defined.864if (SystemDictionary::reflect_CallerSensitive_klass() == NULL || depth != JVM_CALLER_DEPTH) {865Klass* k = thread->security_get_caller_class(depth);866return (k == NULL) ? NULL : (jclass) JNIHandles::make_local(env, k->java_mirror());867}868869// Getting the class of the caller frame.870//871// The call stack at this point looks something like this:872//873// [0] [ @CallerSensitive public sun.reflect.Reflection.getCallerClass ]874// [1] [ @CallerSensitive API.method ]875// [.] [ (skipped intermediate frames) ]876// [n] [ caller ]877vframeStream vfst(thread);878// Cf. LibraryCallKit::inline_native_Reflection_getCallerClass879for (int n = 0; !vfst.at_end(); vfst.security_next(), n++) {880Method* m = vfst.method();881assert(m != NULL, "sanity");882switch (n) {883case 0:884// This must only be called from Reflection.getCallerClass885if (m->intrinsic_id() != vmIntrinsics::_getCallerClass) {886THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), "JVM_GetCallerClass must only be called from Reflection.getCallerClass");887}888// fall-through889case 1:890// Frame 0 and 1 must be caller sensitive.891if (!m->caller_sensitive()) {892THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), err_msg("CallerSensitive annotation expected at frame %d", n));893}894break;895default:896if (!m->is_ignored_by_security_stack_walk()) {897// We have reached the desired frame; return the holder class.898return (jclass) JNIHandles::make_local(env, m->method_holder()->java_mirror());899}900break;901}902}903return NULL;904JVM_END905906907JVM_ENTRY(jclass, JVM_FindPrimitiveClass(JNIEnv* env, const char* utf))908JVMWrapper("JVM_FindPrimitiveClass");909oop mirror = NULL;910BasicType t = name2type(utf);911if (t != T_ILLEGAL && t != T_OBJECT && t != T_ARRAY) {912mirror = Universe::java_mirror(t);913}914if (mirror == NULL) {915THROW_MSG_0(vmSymbols::java_lang_ClassNotFoundException(), (char*) utf);916} else {917return (jclass) JNIHandles::make_local(env, mirror);918}919JVM_END920921922JVM_ENTRY(void, JVM_ResolveClass(JNIEnv* env, jclass cls))923JVMWrapper("JVM_ResolveClass");924if (PrintJVMWarnings) warning("JVM_ResolveClass not implemented");925JVM_END926927928JVM_ENTRY(jboolean, JVM_KnownToNotExist(JNIEnv *env, jobject loader, const char *classname))929JVMWrapper("JVM_KnownToNotExist");930#if INCLUDE_CDS931return ClassLoaderExt::known_to_not_exist(env, loader, classname, THREAD);932#else933return false;934#endif935JVM_END936937938JVM_ENTRY(jobjectArray, JVM_GetResourceLookupCacheURLs(JNIEnv *env, jobject loader))939JVMWrapper("JVM_GetResourceLookupCacheURLs");940#if INCLUDE_CDS941return ClassLoaderExt::get_lookup_cache_urls(env, loader, THREAD);942#else943return NULL;944#endif945JVM_END946947948JVM_ENTRY(jintArray, JVM_GetResourceLookupCache(JNIEnv *env, jobject loader, const char *resource_name))949JVMWrapper("JVM_GetResourceLookupCache");950#if INCLUDE_CDS951return ClassLoaderExt::get_lookup_cache(env, loader, resource_name, THREAD);952#else953return NULL;954#endif955JVM_END956957958// Returns a class loaded by the bootstrap class loader; or null959// if not found. ClassNotFoundException is not thrown.960//961// Rationale behind JVM_FindClassFromBootLoader962// a> JVM_FindClassFromClassLoader was never exported in the export tables.963// b> because of (a) java.dll has a direct dependecy on the unexported964// private symbol "_JVM_FindClassFromClassLoader@20".965// c> the launcher cannot use the private symbol as it dynamically opens966// the entry point, so if something changes, the launcher will fail967// unexpectedly at runtime, it is safest for the launcher to dlopen a968// stable exported interface.969// d> re-exporting JVM_FindClassFromClassLoader as public, will cause its970// signature to change from _JVM_FindClassFromClassLoader@20 to971// JVM_FindClassFromClassLoader and will not be backward compatible972// with older JDKs.973// Thus a public/stable exported entry point is the right solution,974// public here means public in linker semantics, and is exported only975// to the JDK, and is not intended to be a public API.976977JVM_ENTRY(jclass, JVM_FindClassFromBootLoader(JNIEnv* env,978const char* name))979JVMWrapper2("JVM_FindClassFromBootLoader %s", name);980981// Java libraries should ensure that name is never null...982if (name == NULL || (int)strlen(name) > Symbol::max_length()) {983// It's impossible to create this class; the name cannot fit984// into the constant pool.985return NULL;986}987988TempNewSymbol h_name = SymbolTable::new_symbol(name, CHECK_NULL);989Klass* k = SystemDictionary::resolve_or_null(h_name, CHECK_NULL);990if (k == NULL) {991return NULL;992}993994if (TraceClassResolution) {995trace_class_resolution(k);996}997return (jclass) JNIHandles::make_local(env, k->java_mirror());998JVM_END9991000// Not used; JVM_FindClassFromCaller replaces this.1001JVM_ENTRY(jclass, JVM_FindClassFromClassLoader(JNIEnv* env, const char* name,1002jboolean init, jobject loader,1003jboolean throwError))1004JVMWrapper3("JVM_FindClassFromClassLoader %s throw %s", name,1005throwError ? "error" : "exception");1006// Java libraries should ensure that name is never null...1007if (name == NULL || (int)strlen(name) > Symbol::max_length()) {1008// It's impossible to create this class; the name cannot fit1009// into the constant pool.1010if (throwError) {1011THROW_MSG_0(vmSymbols::java_lang_NoClassDefFoundError(), name);1012} else {1013THROW_MSG_0(vmSymbols::java_lang_ClassNotFoundException(), name);1014}1015}1016TempNewSymbol h_name = SymbolTable::new_symbol(name, CHECK_NULL);1017Handle h_loader(THREAD, JNIHandles::resolve(loader));1018jclass result = find_class_from_class_loader(env, h_name, init, h_loader,1019Handle(), throwError, THREAD);10201021if (TraceClassResolution && result != NULL) {1022trace_class_resolution(java_lang_Class::as_Klass(JNIHandles::resolve_non_null(result)));1023}1024return result;1025JVM_END10261027// Find a class with this name in this loader, using the caller's protection domain.1028JVM_ENTRY(jclass, JVM_FindClassFromCaller(JNIEnv* env, const char* name,1029jboolean init, jobject loader,1030jclass caller))1031JVMWrapper2("JVM_FindClassFromCaller %s throws ClassNotFoundException", name);1032// Java libraries should ensure that name is never null...1033if (name == NULL || (int)strlen(name) > Symbol::max_length()) {1034// It's impossible to create this class; the name cannot fit1035// into the constant pool.1036THROW_MSG_0(vmSymbols::java_lang_ClassNotFoundException(), name);1037}10381039TempNewSymbol h_name = SymbolTable::new_symbol(name, CHECK_NULL);10401041oop loader_oop = JNIHandles::resolve(loader);1042oop from_class = JNIHandles::resolve(caller);1043oop protection_domain = NULL;1044// If loader is null, shouldn't call ClassLoader.checkPackageAccess; otherwise get1045// NPE. Put it in another way, the bootstrap class loader has all permission and1046// thus no checkPackageAccess equivalence in the VM class loader.1047// The caller is also passed as NULL by the java code if there is no security1048// manager to avoid the performance cost of getting the calling class.1049if (from_class != NULL && loader_oop != NULL) {1050protection_domain = java_lang_Class::as_Klass(from_class)->protection_domain();1051}10521053Handle h_loader(THREAD, loader_oop);1054Handle h_prot(THREAD, protection_domain);1055jclass result = find_class_from_class_loader(env, h_name, init, h_loader,1056h_prot, false, THREAD);10571058if (TraceClassResolution && result != NULL) {1059trace_class_resolution(java_lang_Class::as_Klass(JNIHandles::resolve_non_null(result)));1060}1061return result;1062JVM_END10631064JVM_ENTRY(jclass, JVM_FindClassFromClass(JNIEnv *env, const char *name,1065jboolean init, jclass from))1066JVMWrapper2("JVM_FindClassFromClass %s", name);1067if (name == NULL || (int)strlen(name) > Symbol::max_length()) {1068// It's impossible to create this class; the name cannot fit1069// into the constant pool.1070THROW_MSG_0(vmSymbols::java_lang_NoClassDefFoundError(), name);1071}1072TempNewSymbol h_name = SymbolTable::new_symbol(name, CHECK_NULL);1073oop from_class_oop = JNIHandles::resolve(from);1074Klass* from_class = (from_class_oop == NULL)1075? (Klass*)NULL1076: java_lang_Class::as_Klass(from_class_oop);1077oop class_loader = NULL;1078oop protection_domain = NULL;1079if (from_class != NULL) {1080class_loader = from_class->class_loader();1081protection_domain = from_class->protection_domain();1082}1083Handle h_loader(THREAD, class_loader);1084Handle h_prot (THREAD, protection_domain);1085jclass result = find_class_from_class_loader(env, h_name, init, h_loader,1086h_prot, true, thread);10871088if (TraceClassResolution && result != NULL) {1089// this function is generally only used for class loading during verification.1090ResourceMark rm;1091oop from_mirror = JNIHandles::resolve_non_null(from);1092Klass* from_class = java_lang_Class::as_Klass(from_mirror);1093const char * from_name = from_class->external_name();10941095oop mirror = JNIHandles::resolve_non_null(result);1096Klass* to_class = java_lang_Class::as_Klass(mirror);1097const char * to = to_class->external_name();1098tty->print("RESOLVE %s %s (verification)\n", from_name, to);1099}11001101return result;1102JVM_END11031104static void is_lock_held_by_thread(Handle loader, PerfCounter* counter, TRAPS) {1105if (loader.is_null()) {1106return;1107}11081109// check whether the current caller thread holds the lock or not.1110// If not, increment the corresponding counter1111if (ObjectSynchronizer::query_lock_ownership((JavaThread*)THREAD, loader) !=1112ObjectSynchronizer::owner_self) {1113counter->inc();1114}1115}11161117// common code for JVM_DefineClass() and JVM_DefineClassWithSource()1118// and JVM_DefineClassWithSourceCond()1119static jclass jvm_define_class_common(JNIEnv *env, const char *name,1120jobject loader, const jbyte *buf,1121jsize len, jobject pd, const char *source,1122jboolean verify, TRAPS) {1123if (source == NULL) source = "__JVM_DefineClass__";11241125assert(THREAD->is_Java_thread(), "must be a JavaThread");1126JavaThread* jt = (JavaThread*) THREAD;11271128PerfClassTraceTime vmtimer(ClassLoader::perf_define_appclass_time(),1129ClassLoader::perf_define_appclass_selftime(),1130ClassLoader::perf_define_appclasses(),1131jt->get_thread_stat()->perf_recursion_counts_addr(),1132jt->get_thread_stat()->perf_timers_addr(),1133PerfClassTraceTime::DEFINE_CLASS);11341135if (UsePerfData) {1136ClassLoader::perf_app_classfile_bytes_read()->inc(len);1137}11381139// Since exceptions can be thrown, class initialization can take place1140// if name is NULL no check for class name in .class stream has to be made.1141TempNewSymbol class_name = NULL;1142if (name != NULL) {1143const int str_len = (int)strlen(name);1144if (str_len > Symbol::max_length()) {1145// It's impossible to create this class; the name cannot fit1146// into the constant pool.1147THROW_MSG_0(vmSymbols::java_lang_NoClassDefFoundError(), name);1148}1149class_name = SymbolTable::new_symbol(name, str_len, CHECK_NULL);1150}11511152ResourceMark rm(THREAD);1153ClassFileStream st((u1*) buf, len, (char *)source);1154Handle class_loader (THREAD, JNIHandles::resolve(loader));1155if (UsePerfData) {1156is_lock_held_by_thread(class_loader,1157ClassLoader::sync_JVMDefineClassLockFreeCounter(),1158THREAD);1159}1160Handle protection_domain (THREAD, JNIHandles::resolve(pd));1161Klass* k = SystemDictionary::resolve_from_stream(class_name, class_loader,1162protection_domain, &st,1163verify != 0,1164CHECK_NULL);11651166if (TraceClassResolution && k != NULL) {1167trace_class_resolution(k);1168}11691170return (jclass) JNIHandles::make_local(env, k->java_mirror());1171}117211731174JVM_ENTRY(jclass, JVM_DefineClass(JNIEnv *env, const char *name, jobject loader, const jbyte *buf, jsize len, jobject pd))1175JVMWrapper2("JVM_DefineClass %s", name);11761177return jvm_define_class_common(env, name, loader, buf, len, pd, NULL, true, THREAD);1178JVM_END117911801181JVM_ENTRY(jclass, JVM_DefineClassWithSource(JNIEnv *env, const char *name, jobject loader, const jbyte *buf, jsize len, jobject pd, const char *source))1182JVMWrapper2("JVM_DefineClassWithSource %s", name);11831184return jvm_define_class_common(env, name, loader, buf, len, pd, source, true, THREAD);1185JVM_END11861187JVM_ENTRY(jclass, JVM_DefineClassWithSourceCond(JNIEnv *env, const char *name,1188jobject loader, const jbyte *buf,1189jsize len, jobject pd,1190const char *source, jboolean verify))1191JVMWrapper2("JVM_DefineClassWithSourceCond %s", name);11921193return jvm_define_class_common(env, name, loader, buf, len, pd, source, verify, THREAD);1194JVM_END11951196JVM_ENTRY(jclass, JVM_FindLoadedClass(JNIEnv *env, jobject loader, jstring name))1197JVMWrapper("JVM_FindLoadedClass");1198ResourceMark rm(THREAD);11991200Handle h_name (THREAD, JNIHandles::resolve_non_null(name));1201Handle string = java_lang_String::internalize_classname(h_name, CHECK_NULL);12021203const char* str = java_lang_String::as_utf8_string(string());1204// Sanity check, don't expect null1205if (str == NULL) return NULL;12061207const int str_len = (int)strlen(str);1208if (str_len > Symbol::max_length()) {1209// It's impossible to create this class; the name cannot fit1210// into the constant pool.1211return NULL;1212}1213TempNewSymbol klass_name = SymbolTable::new_symbol(str, str_len, CHECK_NULL);12141215// Security Note:1216// The Java level wrapper will perform the necessary security check allowing1217// us to pass the NULL as the initiating class loader.1218Handle h_loader(THREAD, JNIHandles::resolve(loader));1219if (UsePerfData) {1220is_lock_held_by_thread(h_loader,1221ClassLoader::sync_JVMFindLoadedClassLockFreeCounter(),1222THREAD);1223}12241225Klass* k = SystemDictionary::find_instance_or_array_klass(klass_name,1226h_loader,1227Handle(),1228CHECK_NULL);1229#if INCLUDE_CDS1230if (k == NULL) {1231// If the class is not already loaded, try to see if it's in the shared1232// archive for the current classloader (h_loader).1233instanceKlassHandle ik = SystemDictionaryShared::find_or_load_shared_class(1234klass_name, h_loader, CHECK_NULL);1235k = ik();1236}1237#endif1238return (k == NULL) ? NULL :1239(jclass) JNIHandles::make_local(env, k->java_mirror());1240JVM_END124112421243// Reflection support //////////////////////////////////////////////////////////////////////////////12441245JVM_ENTRY(jstring, JVM_GetClassName(JNIEnv *env, jclass cls))1246assert (cls != NULL, "illegal class");1247JVMWrapper("JVM_GetClassName");1248JvmtiVMObjectAllocEventCollector oam;1249ResourceMark rm(THREAD);1250const char* name;1251if (java_lang_Class::is_primitive(JNIHandles::resolve(cls))) {1252name = type2name(java_lang_Class::primitive_type(JNIHandles::resolve(cls)));1253} else {1254// Consider caching interned string in Klass1255Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve(cls));1256assert(k->is_klass(), "just checking");1257name = k->external_name();1258}1259oop result = StringTable::intern((char*) name, CHECK_NULL);1260return (jstring) JNIHandles::make_local(env, result);1261JVM_END126212631264JVM_ENTRY(jobjectArray, JVM_GetClassInterfaces(JNIEnv *env, jclass cls))1265JVMWrapper("JVM_GetClassInterfaces");1266JvmtiVMObjectAllocEventCollector oam;1267oop mirror = JNIHandles::resolve_non_null(cls);12681269// Special handling for primitive objects1270if (java_lang_Class::is_primitive(mirror)) {1271// Primitive objects does not have any interfaces1272objArrayOop r = oopFactory::new_objArray(SystemDictionary::Class_klass(), 0, CHECK_NULL);1273return (jobjectArray) JNIHandles::make_local(env, r);1274}12751276KlassHandle klass(thread, java_lang_Class::as_Klass(mirror));1277// Figure size of result array1278int size;1279if (klass->oop_is_instance()) {1280size = InstanceKlass::cast(klass())->local_interfaces()->length();1281} else {1282assert(klass->oop_is_objArray() || klass->oop_is_typeArray(), "Illegal mirror klass");1283size = 2;1284}12851286// Allocate result array1287objArrayOop r = oopFactory::new_objArray(SystemDictionary::Class_klass(), size, CHECK_NULL);1288objArrayHandle result (THREAD, r);1289// Fill in result1290if (klass->oop_is_instance()) {1291// Regular instance klass, fill in all local interfaces1292for (int index = 0; index < size; index++) {1293Klass* k = InstanceKlass::cast(klass())->local_interfaces()->at(index);1294result->obj_at_put(index, k->java_mirror());1295}1296} else {1297// All arrays implement java.lang.Cloneable and java.io.Serializable1298result->obj_at_put(0, SystemDictionary::Cloneable_klass()->java_mirror());1299result->obj_at_put(1, SystemDictionary::Serializable_klass()->java_mirror());1300}1301return (jobjectArray) JNIHandles::make_local(env, result());1302JVM_END130313041305JVM_ENTRY(jobject, JVM_GetClassLoader(JNIEnv *env, jclass cls))1306JVMWrapper("JVM_GetClassLoader");1307if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(cls))) {1308return NULL;1309}1310Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));1311oop loader = k->class_loader();1312return JNIHandles::make_local(env, loader);1313JVM_END131413151316JVM_QUICK_ENTRY(jboolean, JVM_IsInterface(JNIEnv *env, jclass cls))1317JVMWrapper("JVM_IsInterface");1318oop mirror = JNIHandles::resolve_non_null(cls);1319if (java_lang_Class::is_primitive(mirror)) {1320return JNI_FALSE;1321}1322Klass* k = java_lang_Class::as_Klass(mirror);1323jboolean result = k->is_interface();1324assert(!result || k->oop_is_instance(),1325"all interfaces are instance types");1326// The compiler intrinsic for isInterface tests the1327// Klass::_access_flags bits in the same way.1328return result;1329JVM_END133013311332JVM_ENTRY(jobjectArray, JVM_GetClassSigners(JNIEnv *env, jclass cls))1333JVMWrapper("JVM_GetClassSigners");1334JvmtiVMObjectAllocEventCollector oam;1335if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(cls))) {1336// There are no signers for primitive types1337return NULL;1338}13391340objArrayOop signers = java_lang_Class::signers(JNIHandles::resolve_non_null(cls));13411342// If there are no signers set in the class, or if the class1343// is an array, return NULL.1344if (signers == NULL) return NULL;13451346// copy of the signers array1347Klass* element = ObjArrayKlass::cast(signers->klass())->element_klass();1348objArrayOop signers_copy = oopFactory::new_objArray(element, signers->length(), CHECK_NULL);1349for (int index = 0; index < signers->length(); index++) {1350signers_copy->obj_at_put(index, signers->obj_at(index));1351}13521353// return the copy1354return (jobjectArray) JNIHandles::make_local(env, signers_copy);1355JVM_END135613571358JVM_ENTRY(void, JVM_SetClassSigners(JNIEnv *env, jclass cls, jobjectArray signers))1359JVMWrapper("JVM_SetClassSigners");1360if (!java_lang_Class::is_primitive(JNIHandles::resolve_non_null(cls))) {1361// This call is ignored for primitive types and arrays.1362// Signers are only set once, ClassLoader.java, and thus shouldn't1363// be called with an array. Only the bootstrap loader creates arrays.1364Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));1365if (k->oop_is_instance()) {1366java_lang_Class::set_signers(k->java_mirror(), objArrayOop(JNIHandles::resolve(signers)));1367}1368}1369JVM_END137013711372JVM_ENTRY(jobject, JVM_GetProtectionDomain(JNIEnv *env, jclass cls))1373JVMWrapper("JVM_GetProtectionDomain");1374if (JNIHandles::resolve(cls) == NULL) {1375THROW_(vmSymbols::java_lang_NullPointerException(), NULL);1376}13771378if (java_lang_Class::is_primitive(JNIHandles::resolve(cls))) {1379// Primitive types does not have a protection domain.1380return NULL;1381}13821383oop pd = java_lang_Class::protection_domain(JNIHandles::resolve(cls));1384return (jobject) JNIHandles::make_local(env, pd);1385JVM_END138613871388static bool is_authorized(Handle context, instanceKlassHandle klass, TRAPS) {1389// If there is a security manager and protection domain, check the access1390// in the protection domain, otherwise it is authorized.1391if (java_lang_System::has_security_manager()) {13921393// For bootstrapping, if pd implies method isn't in the JDK, allow1394// this context to revert to older behavior.1395// In this case the isAuthorized field in AccessControlContext is also not1396// present.1397if (Universe::protection_domain_implies_method() == NULL) {1398return true;1399}14001401// Whitelist certain access control contexts1402if (java_security_AccessControlContext::is_authorized(context)) {1403return true;1404}14051406oop prot = klass->protection_domain();1407if (prot != NULL) {1408// Call pd.implies(new SecurityPermission("createAccessControlContext"))1409// in the new wrapper.1410methodHandle m(THREAD, Universe::protection_domain_implies_method());1411Handle h_prot(THREAD, prot);1412JavaValue result(T_BOOLEAN);1413JavaCallArguments args(h_prot);1414JavaCalls::call(&result, m, &args, CHECK_false);1415return (result.get_jboolean() != 0);1416}1417}1418return true;1419}14201421// Create an AccessControlContext with a protection domain with null codesource1422// and null permissions - which gives no permissions.1423oop create_dummy_access_control_context(TRAPS) {1424InstanceKlass* pd_klass = InstanceKlass::cast(SystemDictionary::ProtectionDomain_klass());1425Handle obj = pd_klass->allocate_instance_handle(CHECK_NULL);1426// Call constructor ProtectionDomain(null, null);1427JavaValue result(T_VOID);1428JavaCalls::call_special(&result, obj, KlassHandle(THREAD, pd_klass),1429vmSymbols::object_initializer_name(),1430vmSymbols::codesource_permissioncollection_signature(),1431Handle(), Handle(), CHECK_NULL);14321433// new ProtectionDomain[] {pd};1434objArrayOop context = oopFactory::new_objArray(pd_klass, 1, CHECK_NULL);1435context->obj_at_put(0, obj());14361437// new AccessControlContext(new ProtectionDomain[] {pd})1438objArrayHandle h_context(THREAD, context);1439oop acc = java_security_AccessControlContext::create(h_context, false, Handle(), CHECK_NULL);1440return acc;1441}14421443JVM_ENTRY(jobject, JVM_DoPrivileged(JNIEnv *env, jclass cls, jobject action, jobject context, jboolean wrapException))1444JVMWrapper("JVM_DoPrivileged");14451446if (action == NULL) {1447THROW_MSG_0(vmSymbols::java_lang_NullPointerException(), "Null action");1448}14491450// Compute the frame initiating the do privileged operation and setup the privileged stack1451vframeStream vfst(thread);1452vfst.security_get_caller_frame(1);14531454if (vfst.at_end()) {1455THROW_MSG_0(vmSymbols::java_lang_InternalError(), "no caller?");1456}14571458Method* method = vfst.method();1459instanceKlassHandle klass (THREAD, method->method_holder());14601461// Check that action object understands "Object run()"1462Handle h_context;1463if (context != NULL) {1464h_context = Handle(THREAD, JNIHandles::resolve(context));1465bool authorized = is_authorized(h_context, klass, CHECK_NULL);1466if (!authorized) {1467// Create an unprivileged access control object and call it's run function1468// instead.1469oop noprivs = create_dummy_access_control_context(CHECK_NULL);1470h_context = Handle(THREAD, noprivs);1471}1472}14731474// Check that action object understands "Object run()"1475Handle object (THREAD, JNIHandles::resolve(action));14761477// get run() method1478Method* m_oop = object->klass()->uncached_lookup_method(1479vmSymbols::run_method_name(),1480vmSymbols::void_object_signature(),1481Klass::find_overpass);1482methodHandle m (THREAD, m_oop);1483if (m.is_null() || !m->is_method() || !m()->is_public() || m()->is_static()) {1484THROW_MSG_0(vmSymbols::java_lang_InternalError(), "No run method");1485}14861487// Stack allocated list of privileged stack elements1488PrivilegedElement pi;1489if (!vfst.at_end()) {1490pi.initialize(&vfst, h_context(), thread->privileged_stack_top(), CHECK_NULL);1491thread->set_privileged_stack_top(&pi);1492}149314941495// invoke the Object run() in the action object. We cannot use call_interface here, since the static type1496// is not really known - it is either java.security.PrivilegedAction or java.security.PrivilegedExceptionAction1497Handle pending_exception;1498JavaValue result(T_OBJECT);1499JavaCallArguments args(object);1500JavaCalls::call(&result, m, &args, THREAD);15011502// done with action, remove ourselves from the list1503if (!vfst.at_end()) {1504assert(thread->privileged_stack_top() != NULL && thread->privileged_stack_top() == &pi, "wrong top element");1505thread->set_privileged_stack_top(thread->privileged_stack_top()->next());1506}15071508if (HAS_PENDING_EXCEPTION) {1509pending_exception = Handle(THREAD, PENDING_EXCEPTION);1510CLEAR_PENDING_EXCEPTION;1511// JVMTI has already reported the pending exception1512// JVMTI internal flag reset is needed in order to report PrivilegedActionException1513if (THREAD->is_Java_thread()) {1514JvmtiExport::clear_detected_exception((JavaThread*) THREAD);1515}1516if ( pending_exception->is_a(SystemDictionary::Exception_klass()) &&1517!pending_exception->is_a(SystemDictionary::RuntimeException_klass())) {1518// Throw a java.security.PrivilegedActionException(Exception e) exception1519JavaCallArguments args(pending_exception);1520THROW_ARG_0(vmSymbols::java_security_PrivilegedActionException(),1521vmSymbols::exception_void_signature(),1522&args);1523}1524}15251526if (pending_exception.not_null()) THROW_OOP_0(pending_exception());1527return JNIHandles::make_local(env, (oop) result.get_jobject());1528JVM_END152915301531// Returns the inherited_access_control_context field of the running thread.1532JVM_ENTRY(jobject, JVM_GetInheritedAccessControlContext(JNIEnv *env, jclass cls))1533JVMWrapper("JVM_GetInheritedAccessControlContext");1534oop result = java_lang_Thread::inherited_access_control_context(thread->threadObj());1535return JNIHandles::make_local(env, result);1536JVM_END15371538class RegisterArrayForGC {1539private:1540JavaThread *_thread;1541public:1542RegisterArrayForGC(JavaThread *thread, GrowableArray<oop>* array) {1543_thread = thread;1544_thread->register_array_for_gc(array);1545}15461547~RegisterArrayForGC() {1548_thread->register_array_for_gc(NULL);1549}1550};155115521553JVM_ENTRY(jobject, JVM_GetStackAccessControlContext(JNIEnv *env, jclass cls))1554JVMWrapper("JVM_GetStackAccessControlContext");1555if (!UsePrivilegedStack) return NULL;15561557ResourceMark rm(THREAD);1558GrowableArray<oop>* local_array = new GrowableArray<oop>(12);1559JvmtiVMObjectAllocEventCollector oam;15601561// count the protection domains on the execution stack. We collapse1562// duplicate consecutive protection domains into a single one, as1563// well as stopping when we hit a privileged frame.15641565// Use vframeStream to iterate through Java frames1566vframeStream vfst(thread);15671568oop previous_protection_domain = NULL;1569Handle privileged_context(thread, NULL);1570bool is_privileged = false;1571oop protection_domain = NULL;15721573for(; !vfst.at_end(); vfst.next()) {1574// get method of frame1575Method* method = vfst.method();1576intptr_t* frame_id = vfst.frame_id();15771578// check the privileged frames to see if we have a match1579if (thread->privileged_stack_top() && thread->privileged_stack_top()->frame_id() == frame_id) {1580// this frame is privileged1581is_privileged = true;1582privileged_context = Handle(thread, thread->privileged_stack_top()->privileged_context());1583protection_domain = thread->privileged_stack_top()->protection_domain();1584} else {1585protection_domain = method->method_holder()->protection_domain();1586}15871588if ((previous_protection_domain != protection_domain) && (protection_domain != NULL)) {1589local_array->push(protection_domain);1590previous_protection_domain = protection_domain;1591}15921593if (is_privileged) break;1594}159515961597// either all the domains on the stack were system domains, or1598// we had a privileged system domain1599if (local_array->is_empty()) {1600if (is_privileged && privileged_context.is_null()) return NULL;16011602oop result = java_security_AccessControlContext::create(objArrayHandle(), is_privileged, privileged_context, CHECK_NULL);1603return JNIHandles::make_local(env, result);1604}16051606// the resource area must be registered in case of a gc1607RegisterArrayForGC ragc(thread, local_array);1608objArrayOop context = oopFactory::new_objArray(SystemDictionary::ProtectionDomain_klass(),1609local_array->length(), CHECK_NULL);1610objArrayHandle h_context(thread, context);1611for (int index = 0; index < local_array->length(); index++) {1612h_context->obj_at_put(index, local_array->at(index));1613}16141615oop result = java_security_AccessControlContext::create(h_context, is_privileged, privileged_context, CHECK_NULL);16161617return JNIHandles::make_local(env, result);1618JVM_END161916201621JVM_QUICK_ENTRY(jboolean, JVM_IsArrayClass(JNIEnv *env, jclass cls))1622JVMWrapper("JVM_IsArrayClass");1623Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));1624return (k != NULL) && k->oop_is_array() ? true : false;1625JVM_END162616271628JVM_QUICK_ENTRY(jboolean, JVM_IsPrimitiveClass(JNIEnv *env, jclass cls))1629JVMWrapper("JVM_IsPrimitiveClass");1630oop mirror = JNIHandles::resolve_non_null(cls);1631return (jboolean) java_lang_Class::is_primitive(mirror);1632JVM_END163316341635JVM_ENTRY(jclass, JVM_GetComponentType(JNIEnv *env, jclass cls))1636JVMWrapper("JVM_GetComponentType");1637oop mirror = JNIHandles::resolve_non_null(cls);1638oop result = Reflection::array_component_type(mirror, CHECK_NULL);1639return (jclass) JNIHandles::make_local(env, result);1640JVM_END164116421643JVM_ENTRY(jint, JVM_GetClassModifiers(JNIEnv *env, jclass cls))1644JVMWrapper("JVM_GetClassModifiers");1645if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(cls))) {1646// Primitive type1647return JVM_ACC_ABSTRACT | JVM_ACC_FINAL | JVM_ACC_PUBLIC;1648}16491650Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));1651debug_only(int computed_modifiers = k->compute_modifier_flags(CHECK_0));1652assert(k->modifier_flags() == computed_modifiers, "modifiers cache is OK");1653return k->modifier_flags();1654JVM_END165516561657// Inner class reflection ///////////////////////////////////////////////////////////////////////////////16581659JVM_ENTRY(jobjectArray, JVM_GetDeclaredClasses(JNIEnv *env, jclass ofClass))1660JvmtiVMObjectAllocEventCollector oam;1661// ofClass is a reference to a java_lang_Class object. The mirror object1662// of an InstanceKlass16631664if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(ofClass)) ||1665! java_lang_Class::as_Klass(JNIHandles::resolve_non_null(ofClass))->oop_is_instance()) {1666oop result = oopFactory::new_objArray(SystemDictionary::Class_klass(), 0, CHECK_NULL);1667return (jobjectArray)JNIHandles::make_local(env, result);1668}16691670instanceKlassHandle k(thread, java_lang_Class::as_Klass(JNIHandles::resolve_non_null(ofClass)));1671InnerClassesIterator iter(k);16721673if (iter.length() == 0) {1674// Neither an inner nor outer class1675oop result = oopFactory::new_objArray(SystemDictionary::Class_klass(), 0, CHECK_NULL);1676return (jobjectArray)JNIHandles::make_local(env, result);1677}16781679// find inner class info1680constantPoolHandle cp(thread, k->constants());1681int length = iter.length();16821683// Allocate temp. result array1684objArrayOop r = oopFactory::new_objArray(SystemDictionary::Class_klass(), length/4, CHECK_NULL);1685objArrayHandle result (THREAD, r);1686int members = 0;16871688for (; !iter.done(); iter.next()) {1689int ioff = iter.inner_class_info_index();1690int ooff = iter.outer_class_info_index();16911692if (ioff != 0 && ooff != 0) {1693// Check to see if the name matches the class we're looking for1694// before attempting to find the class.1695if (cp->klass_name_at_matches(k, ooff)) {1696Klass* outer_klass = cp->klass_at(ooff, CHECK_NULL);1697if (outer_klass == k()) {1698Klass* ik = cp->klass_at(ioff, CHECK_NULL);1699instanceKlassHandle inner_klass (THREAD, ik);17001701// Throws an exception if outer klass has not declared k as1702// an inner klass1703Reflection::check_for_inner_class(k, inner_klass, true, CHECK_NULL);17041705result->obj_at_put(members, inner_klass->java_mirror());1706members++;1707}1708}1709}1710}17111712if (members != length) {1713// Return array of right length1714objArrayOop res = oopFactory::new_objArray(SystemDictionary::Class_klass(), members, CHECK_NULL);1715for(int i = 0; i < members; i++) {1716res->obj_at_put(i, result->obj_at(i));1717}1718return (jobjectArray)JNIHandles::make_local(env, res);1719}17201721return (jobjectArray)JNIHandles::make_local(env, result());1722JVM_END172317241725JVM_ENTRY(jclass, JVM_GetDeclaringClass(JNIEnv *env, jclass ofClass))1726{1727// ofClass is a reference to a java_lang_Class object.1728if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(ofClass)) ||1729! java_lang_Class::as_Klass(JNIHandles::resolve_non_null(ofClass))->oop_is_instance()) {1730return NULL;1731}17321733bool inner_is_member = false;1734Klass* outer_klass1735= InstanceKlass::cast(java_lang_Class::as_Klass(JNIHandles::resolve_non_null(ofClass))1736)->compute_enclosing_class(&inner_is_member, CHECK_NULL);1737if (outer_klass == NULL) return NULL; // already a top-level class1738if (!inner_is_member) return NULL; // an anonymous class (inside a method)1739return (jclass) JNIHandles::make_local(env, outer_klass->java_mirror());1740}1741JVM_END17421743// should be in InstanceKlass.cpp, but is here for historical reasons1744Klass* InstanceKlass::compute_enclosing_class_impl(instanceKlassHandle k,1745bool* inner_is_member,1746TRAPS) {1747Thread* thread = THREAD;1748InnerClassesIterator iter(k);1749if (iter.length() == 0) {1750// No inner class info => no declaring class1751return NULL;1752}17531754constantPoolHandle i_cp(thread, k->constants());17551756bool found = false;1757Klass* ok;1758instanceKlassHandle outer_klass;1759*inner_is_member = false;17601761// Find inner_klass attribute1762for (; !iter.done() && !found; iter.next()) {1763int ioff = iter.inner_class_info_index();1764int ooff = iter.outer_class_info_index();1765int noff = iter.inner_name_index();1766if (ioff != 0) {1767// Check to see if the name matches the class we're looking for1768// before attempting to find the class.1769if (i_cp->klass_name_at_matches(k, ioff)) {1770Klass* inner_klass = i_cp->klass_at(ioff, CHECK_NULL);1771found = (k() == inner_klass);1772if (found && ooff != 0) {1773ok = i_cp->klass_at(ooff, CHECK_NULL);1774outer_klass = instanceKlassHandle(thread, ok);1775*inner_is_member = true;1776}1777}1778}1779}17801781if (found && outer_klass.is_null()) {1782// It may be anonymous; try for that.1783int encl_method_class_idx = k->enclosing_method_class_index();1784if (encl_method_class_idx != 0) {1785ok = i_cp->klass_at(encl_method_class_idx, CHECK_NULL);1786outer_klass = instanceKlassHandle(thread, ok);1787*inner_is_member = false;1788}1789}17901791// If no inner class attribute found for this class.1792if (outer_klass.is_null()) return NULL;17931794// Throws an exception if outer klass has not declared k as an inner klass1795// We need evidence that each klass knows about the other, or else1796// the system could allow a spoof of an inner class to gain access rights.1797Reflection::check_for_inner_class(outer_klass, k, *inner_is_member, CHECK_NULL);1798return outer_klass();1799}18001801JVM_ENTRY(jstring, JVM_GetClassSignature(JNIEnv *env, jclass cls))1802assert (cls != NULL, "illegal class");1803JVMWrapper("JVM_GetClassSignature");1804JvmtiVMObjectAllocEventCollector oam;1805ResourceMark rm(THREAD);1806// Return null for arrays and primatives1807if (!java_lang_Class::is_primitive(JNIHandles::resolve(cls))) {1808Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve(cls));1809if (k->oop_is_instance()) {1810Symbol* sym = InstanceKlass::cast(k)->generic_signature();1811if (sym == NULL) return NULL;1812Handle str = java_lang_String::create_from_symbol(sym, CHECK_NULL);1813return (jstring) JNIHandles::make_local(env, str());1814}1815}1816return NULL;1817JVM_END181818191820JVM_ENTRY(jbyteArray, JVM_GetClassAnnotations(JNIEnv *env, jclass cls))1821assert (cls != NULL, "illegal class");1822JVMWrapper("JVM_GetClassAnnotations");18231824// Return null for arrays and primitives1825if (!java_lang_Class::is_primitive(JNIHandles::resolve(cls))) {1826Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve(cls));1827if (k->oop_is_instance()) {1828typeArrayOop a = Annotations::make_java_array(InstanceKlass::cast(k)->class_annotations(), CHECK_NULL);1829return (jbyteArray) JNIHandles::make_local(env, a);1830}1831}1832return NULL;1833JVM_END183418351836static bool jvm_get_field_common(jobject field, fieldDescriptor& fd, TRAPS) {1837// some of this code was adapted from from jni_FromReflectedField18381839oop reflected = JNIHandles::resolve_non_null(field);1840oop mirror = java_lang_reflect_Field::clazz(reflected);1841Klass* k = java_lang_Class::as_Klass(mirror);1842int slot = java_lang_reflect_Field::slot(reflected);1843int modifiers = java_lang_reflect_Field::modifiers(reflected);18441845KlassHandle kh(THREAD, k);1846intptr_t offset = InstanceKlass::cast(kh())->field_offset(slot);18471848if (modifiers & JVM_ACC_STATIC) {1849// for static fields we only look in the current class1850if (!InstanceKlass::cast(kh())->find_local_field_from_offset(offset, true, &fd)) {1851assert(false, "cannot find static field");1852return false;1853}1854} else {1855// for instance fields we start with the current class and work1856// our way up through the superclass chain1857if (!InstanceKlass::cast(kh())->find_field_from_offset(offset, false, &fd)) {1858assert(false, "cannot find instance field");1859return false;1860}1861}1862return true;1863}18641865JVM_ENTRY(jbyteArray, JVM_GetFieldAnnotations(JNIEnv *env, jobject field))1866// field is a handle to a java.lang.reflect.Field object1867assert(field != NULL, "illegal field");1868JVMWrapper("JVM_GetFieldAnnotations");18691870fieldDescriptor fd;1871bool gotFd = jvm_get_field_common(field, fd, CHECK_NULL);1872if (!gotFd) {1873return NULL;1874}18751876return (jbyteArray) JNIHandles::make_local(env, Annotations::make_java_array(fd.annotations(), THREAD));1877JVM_END187818791880static Method* jvm_get_method_common(jobject method) {1881// some of this code was adapted from from jni_FromReflectedMethod18821883oop reflected = JNIHandles::resolve_non_null(method);1884oop mirror = NULL;1885int slot = 0;18861887if (reflected->klass() == SystemDictionary::reflect_Constructor_klass()) {1888mirror = java_lang_reflect_Constructor::clazz(reflected);1889slot = java_lang_reflect_Constructor::slot(reflected);1890} else {1891assert(reflected->klass() == SystemDictionary::reflect_Method_klass(),1892"wrong type");1893mirror = java_lang_reflect_Method::clazz(reflected);1894slot = java_lang_reflect_Method::slot(reflected);1895}1896Klass* k = java_lang_Class::as_Klass(mirror);18971898Method* m = InstanceKlass::cast(k)->method_with_idnum(slot);1899assert(m != NULL, "cannot find method");1900return m; // caller has to deal with NULL in product mode1901}190219031904JVM_ENTRY(jbyteArray, JVM_GetMethodAnnotations(JNIEnv *env, jobject method))1905JVMWrapper("JVM_GetMethodAnnotations");19061907// method is a handle to a java.lang.reflect.Method object1908Method* m = jvm_get_method_common(method);1909if (m == NULL) {1910return NULL;1911}19121913return (jbyteArray) JNIHandles::make_local(env,1914Annotations::make_java_array(m->annotations(), THREAD));1915JVM_END191619171918JVM_ENTRY(jbyteArray, JVM_GetMethodDefaultAnnotationValue(JNIEnv *env, jobject method))1919JVMWrapper("JVM_GetMethodDefaultAnnotationValue");19201921// method is a handle to a java.lang.reflect.Method object1922Method* m = jvm_get_method_common(method);1923if (m == NULL) {1924return NULL;1925}19261927return (jbyteArray) JNIHandles::make_local(env,1928Annotations::make_java_array(m->annotation_default(), THREAD));1929JVM_END193019311932JVM_ENTRY(jbyteArray, JVM_GetMethodParameterAnnotations(JNIEnv *env, jobject method))1933JVMWrapper("JVM_GetMethodParameterAnnotations");19341935// method is a handle to a java.lang.reflect.Method object1936Method* m = jvm_get_method_common(method);1937if (m == NULL) {1938return NULL;1939}19401941return (jbyteArray) JNIHandles::make_local(env,1942Annotations::make_java_array(m->parameter_annotations(), THREAD));1943JVM_END19441945/* Type use annotations support (JDK 1.8) */19461947JVM_ENTRY(jbyteArray, JVM_GetClassTypeAnnotations(JNIEnv *env, jclass cls))1948assert (cls != NULL, "illegal class");1949JVMWrapper("JVM_GetClassTypeAnnotations");1950ResourceMark rm(THREAD);1951// Return null for arrays and primitives1952if (!java_lang_Class::is_primitive(JNIHandles::resolve(cls))) {1953Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve(cls));1954if (k->oop_is_instance()) {1955AnnotationArray* type_annotations = InstanceKlass::cast(k)->class_type_annotations();1956if (type_annotations != NULL) {1957typeArrayOop a = Annotations::make_java_array(type_annotations, CHECK_NULL);1958return (jbyteArray) JNIHandles::make_local(env, a);1959}1960}1961}1962return NULL;1963JVM_END19641965JVM_ENTRY(jbyteArray, JVM_GetMethodTypeAnnotations(JNIEnv *env, jobject method))1966assert (method != NULL, "illegal method");1967JVMWrapper("JVM_GetMethodTypeAnnotations");19681969// method is a handle to a java.lang.reflect.Method object1970Method* m = jvm_get_method_common(method);1971if (m == NULL) {1972return NULL;1973}19741975AnnotationArray* type_annotations = m->type_annotations();1976if (type_annotations != NULL) {1977typeArrayOop a = Annotations::make_java_array(type_annotations, CHECK_NULL);1978return (jbyteArray) JNIHandles::make_local(env, a);1979}19801981return NULL;1982JVM_END19831984JVM_ENTRY(jbyteArray, JVM_GetFieldTypeAnnotations(JNIEnv *env, jobject field))1985assert (field != NULL, "illegal field");1986JVMWrapper("JVM_GetFieldTypeAnnotations");19871988fieldDescriptor fd;1989bool gotFd = jvm_get_field_common(field, fd, CHECK_NULL);1990if (!gotFd) {1991return NULL;1992}19931994return (jbyteArray) JNIHandles::make_local(env, Annotations::make_java_array(fd.type_annotations(), THREAD));1995JVM_END19961997static void bounds_check(constantPoolHandle cp, jint index, TRAPS) {1998if (!cp->is_within_bounds(index)) {1999THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "Constant pool index out of bounds");2000}2001}20022003JVM_ENTRY(jobjectArray, JVM_GetMethodParameters(JNIEnv *env, jobject method))2004{2005JVMWrapper("JVM_GetMethodParameters");2006// method is a handle to a java.lang.reflect.Method object2007Method* method_ptr = jvm_get_method_common(method);2008methodHandle mh (THREAD, method_ptr);2009Handle reflected_method (THREAD, JNIHandles::resolve_non_null(method));2010const int num_params = mh->method_parameters_length();20112012if (0 != num_params) {2013// make sure all the symbols are properly formatted2014for (int i = 0; i < num_params; i++) {2015MethodParametersElement* params = mh->method_parameters_start();2016int index = params[i].name_cp_index;2017bounds_check(mh->constants(), index, CHECK_NULL);20182019if (0 != index && !mh->constants()->tag_at(index).is_utf8()) {2020THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),2021"Wrong type at constant pool index");2022}20232024}20252026objArrayOop result_oop = oopFactory::new_objArray(SystemDictionary::reflect_Parameter_klass(), num_params, CHECK_NULL);2027objArrayHandle result (THREAD, result_oop);20282029for (int i = 0; i < num_params; i++) {2030MethodParametersElement* params = mh->method_parameters_start();2031// For a 0 index, give a NULL symbol2032Symbol* sym = 0 != params[i].name_cp_index ?2033mh->constants()->symbol_at(params[i].name_cp_index) : NULL;2034int flags = params[i].flags;2035oop param = Reflection::new_parameter(reflected_method, i, sym,2036flags, CHECK_NULL);2037result->obj_at_put(i, param);2038}2039return (jobjectArray)JNIHandles::make_local(env, result());2040} else {2041return (jobjectArray)NULL;2042}2043}2044JVM_END20452046// New (JDK 1.4) reflection implementation /////////////////////////////////////20472048JVM_ENTRY(jobjectArray, JVM_GetClassDeclaredFields(JNIEnv *env, jclass ofClass, jboolean publicOnly))2049{2050JVMWrapper("JVM_GetClassDeclaredFields");2051JvmtiVMObjectAllocEventCollector oam;20522053// Exclude primitive types and array types2054if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(ofClass)) ||2055java_lang_Class::as_Klass(JNIHandles::resolve_non_null(ofClass))->oop_is_array()) {2056// Return empty array2057oop res = oopFactory::new_objArray(SystemDictionary::reflect_Field_klass(), 0, CHECK_NULL);2058return (jobjectArray) JNIHandles::make_local(env, res);2059}20602061instanceKlassHandle k(THREAD, java_lang_Class::as_Klass(JNIHandles::resolve_non_null(ofClass)));2062constantPoolHandle cp(THREAD, k->constants());20632064// Ensure class is linked2065k->link_class(CHECK_NULL);20662067// 4496456 We need to filter out java.lang.Throwable.backtrace2068bool skip_backtrace = false;20692070// Allocate result2071int num_fields;20722073if (publicOnly) {2074num_fields = 0;2075for (JavaFieldStream fs(k()); !fs.done(); fs.next()) {2076if (fs.access_flags().is_public()) ++num_fields;2077}2078} else {2079num_fields = k->java_fields_count();20802081if (k() == SystemDictionary::Throwable_klass()) {2082num_fields--;2083skip_backtrace = true;2084}2085}20862087objArrayOop r = oopFactory::new_objArray(SystemDictionary::reflect_Field_klass(), num_fields, CHECK_NULL);2088objArrayHandle result (THREAD, r);20892090int out_idx = 0;2091fieldDescriptor fd;2092for (JavaFieldStream fs(k); !fs.done(); fs.next()) {2093if (skip_backtrace) {2094// 4496456 skip java.lang.Throwable.backtrace2095int offset = fs.offset();2096if (offset == java_lang_Throwable::get_backtrace_offset()) continue;2097}20982099if (!publicOnly || fs.access_flags().is_public()) {2100fd.reinitialize(k(), fs.index());2101oop field = Reflection::new_field(&fd, UseNewReflection, CHECK_NULL);2102result->obj_at_put(out_idx, field);2103++out_idx;2104}2105}2106assert(out_idx == num_fields, "just checking");2107return (jobjectArray) JNIHandles::make_local(env, result());2108}2109JVM_END21102111static bool select_method(methodHandle method, bool want_constructor) {2112if (want_constructor) {2113return (method->is_initializer() && !method->is_static());2114} else {2115return (!method->is_initializer() && !method->is_overpass());2116}2117}21182119static jobjectArray get_class_declared_methods_helper(2120JNIEnv *env,2121jclass ofClass, jboolean publicOnly,2122bool want_constructor,2123Klass* klass, TRAPS) {21242125JvmtiVMObjectAllocEventCollector oam;21262127// Exclude primitive types and array types2128if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(ofClass))2129|| java_lang_Class::as_Klass(JNIHandles::resolve_non_null(ofClass))->oop_is_array()) {2130// Return empty array2131oop res = oopFactory::new_objArray(klass, 0, CHECK_NULL);2132return (jobjectArray) JNIHandles::make_local(env, res);2133}21342135instanceKlassHandle k(THREAD, java_lang_Class::as_Klass(JNIHandles::resolve_non_null(ofClass)));21362137// Ensure class is linked2138k->link_class(CHECK_NULL);21392140Array<Method*>* methods = k->methods();2141int methods_length = methods->length();21422143// Save original method_idnum in case of redefinition, which can change2144// the idnum of obsolete methods. The new method will have the same idnum2145// but if we refresh the methods array, the counts will be wrong.2146ResourceMark rm(THREAD);2147GrowableArray<int>* idnums = new GrowableArray<int>(methods_length);2148int num_methods = 0;21492150for (int i = 0; i < methods_length; i++) {2151methodHandle method(THREAD, methods->at(i));2152if (select_method(method, want_constructor)) {2153if (!publicOnly || method->is_public()) {2154idnums->push(method->method_idnum());2155++num_methods;2156}2157}2158}21592160// Allocate result2161objArrayOop r = oopFactory::new_objArray(klass, num_methods, CHECK_NULL);2162objArrayHandle result (THREAD, r);21632164// Now just put the methods that we selected above, but go by their idnum2165// in case of redefinition. The methods can be redefined at any safepoint,2166// so above when allocating the oop array and below when creating reflect2167// objects.2168for (int i = 0; i < num_methods; i++) {2169methodHandle method(THREAD, k->method_with_idnum(idnums->at(i)));2170if (method.is_null()) {2171// Method may have been deleted and seems this API can handle null2172// Otherwise should probably put a method that throws NSME2173result->obj_at_put(i, NULL);2174} else {2175oop m;2176if (want_constructor) {2177m = Reflection::new_constructor(method, CHECK_NULL);2178} else {2179m = Reflection::new_method(method, UseNewReflection, false, CHECK_NULL);2180}2181result->obj_at_put(i, m);2182}2183}21842185return (jobjectArray) JNIHandles::make_local(env, result());2186}21872188JVM_ENTRY(jobjectArray, JVM_GetClassDeclaredMethods(JNIEnv *env, jclass ofClass, jboolean publicOnly))2189{2190JVMWrapper("JVM_GetClassDeclaredMethods");2191return get_class_declared_methods_helper(env, ofClass, publicOnly,2192/*want_constructor*/ false,2193SystemDictionary::reflect_Method_klass(), THREAD);2194}2195JVM_END21962197JVM_ENTRY(jobjectArray, JVM_GetClassDeclaredConstructors(JNIEnv *env, jclass ofClass, jboolean publicOnly))2198{2199JVMWrapper("JVM_GetClassDeclaredConstructors");2200return get_class_declared_methods_helper(env, ofClass, publicOnly,2201/*want_constructor*/ true,2202SystemDictionary::reflect_Constructor_klass(), THREAD);2203}2204JVM_END22052206JVM_ENTRY(jint, JVM_GetClassAccessFlags(JNIEnv *env, jclass cls))2207{2208JVMWrapper("JVM_GetClassAccessFlags");2209if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(cls))) {2210// Primitive type2211return JVM_ACC_ABSTRACT | JVM_ACC_FINAL | JVM_ACC_PUBLIC;2212}22132214Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));2215return k->access_flags().as_int() & JVM_ACC_WRITTEN_FLAGS;2216}2217JVM_END221822192220// Constant pool access //////////////////////////////////////////////////////////22212222JVM_ENTRY(jobject, JVM_GetClassConstantPool(JNIEnv *env, jclass cls))2223{2224JVMWrapper("JVM_GetClassConstantPool");2225JvmtiVMObjectAllocEventCollector oam;22262227// Return null for primitives and arrays2228if (!java_lang_Class::is_primitive(JNIHandles::resolve_non_null(cls))) {2229Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));2230if (k->oop_is_instance()) {2231instanceKlassHandle k_h(THREAD, k);2232Handle jcp = sun_reflect_ConstantPool::create(CHECK_NULL);2233sun_reflect_ConstantPool::set_cp(jcp(), k_h->constants());2234return JNIHandles::make_local(jcp());2235}2236}2237return NULL;2238}2239JVM_END224022412242JVM_ENTRY(jint, JVM_ConstantPoolGetSize(JNIEnv *env, jobject obj, jobject unused))2243{2244JVMWrapper("JVM_ConstantPoolGetSize");2245constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));2246return cp->length();2247}2248JVM_END224922502251JVM_ENTRY(jclass, JVM_ConstantPoolGetClassAt(JNIEnv *env, jobject obj, jobject unused, jint index))2252{2253JVMWrapper("JVM_ConstantPoolGetClassAt");2254constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));2255bounds_check(cp, index, CHECK_NULL);2256constantTag tag = cp->tag_at(index);2257if (!tag.is_klass() && !tag.is_unresolved_klass()) {2258THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");2259}2260Klass* k = cp->klass_at(index, CHECK_NULL);2261return (jclass) JNIHandles::make_local(k->java_mirror());2262}2263JVM_END22642265JVM_ENTRY(jclass, JVM_ConstantPoolGetClassAtIfLoaded(JNIEnv *env, jobject obj, jobject unused, jint index))2266{2267JVMWrapper("JVM_ConstantPoolGetClassAtIfLoaded");2268constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));2269bounds_check(cp, index, CHECK_NULL);2270constantTag tag = cp->tag_at(index);2271if (!tag.is_klass() && !tag.is_unresolved_klass()) {2272THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");2273}2274Klass* k = ConstantPool::klass_at_if_loaded(cp, index);2275if (k == NULL) return NULL;2276return (jclass) JNIHandles::make_local(k->java_mirror());2277}2278JVM_END22792280static jobject get_method_at_helper(constantPoolHandle cp, jint index, bool force_resolution, TRAPS) {2281constantTag tag = cp->tag_at(index);2282if (!tag.is_method() && !tag.is_interface_method()) {2283THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");2284}2285int klass_ref = cp->uncached_klass_ref_index_at(index);2286Klass* k_o;2287if (force_resolution) {2288k_o = cp->klass_at(klass_ref, CHECK_NULL);2289} else {2290k_o = ConstantPool::klass_at_if_loaded(cp, klass_ref);2291if (k_o == NULL) return NULL;2292}2293instanceKlassHandle k(THREAD, k_o);2294Symbol* name = cp->uncached_name_ref_at(index);2295Symbol* sig = cp->uncached_signature_ref_at(index);2296methodHandle m (THREAD, k->find_method(name, sig));2297if (m.is_null()) {2298THROW_MSG_0(vmSymbols::java_lang_RuntimeException(), "Unable to look up method in target class");2299}2300oop method;2301if (!m->is_initializer() || m->is_static()) {2302method = Reflection::new_method(m, true, true, CHECK_NULL);2303} else {2304method = Reflection::new_constructor(m, CHECK_NULL);2305}2306return JNIHandles::make_local(method);2307}23082309JVM_ENTRY(jobject, JVM_ConstantPoolGetMethodAt(JNIEnv *env, jobject obj, jobject unused, jint index))2310{2311JVMWrapper("JVM_ConstantPoolGetMethodAt");2312JvmtiVMObjectAllocEventCollector oam;2313constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));2314bounds_check(cp, index, CHECK_NULL);2315jobject res = get_method_at_helper(cp, index, true, CHECK_NULL);2316return res;2317}2318JVM_END23192320JVM_ENTRY(jobject, JVM_ConstantPoolGetMethodAtIfLoaded(JNIEnv *env, jobject obj, jobject unused, jint index))2321{2322JVMWrapper("JVM_ConstantPoolGetMethodAtIfLoaded");2323JvmtiVMObjectAllocEventCollector oam;2324constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));2325bounds_check(cp, index, CHECK_NULL);2326jobject res = get_method_at_helper(cp, index, false, CHECK_NULL);2327return res;2328}2329JVM_END23302331static jobject get_field_at_helper(constantPoolHandle cp, jint index, bool force_resolution, TRAPS) {2332constantTag tag = cp->tag_at(index);2333if (!tag.is_field()) {2334THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");2335}2336int klass_ref = cp->uncached_klass_ref_index_at(index);2337Klass* k_o;2338if (force_resolution) {2339k_o = cp->klass_at(klass_ref, CHECK_NULL);2340} else {2341k_o = ConstantPool::klass_at_if_loaded(cp, klass_ref);2342if (k_o == NULL) return NULL;2343}2344instanceKlassHandle k(THREAD, k_o);2345Symbol* name = cp->uncached_name_ref_at(index);2346Symbol* sig = cp->uncached_signature_ref_at(index);2347fieldDescriptor fd;2348Klass* target_klass = k->find_field(name, sig, &fd);2349if (target_klass == NULL) {2350THROW_MSG_0(vmSymbols::java_lang_RuntimeException(), "Unable to look up field in target class");2351}2352oop field = Reflection::new_field(&fd, true, CHECK_NULL);2353return JNIHandles::make_local(field);2354}23552356JVM_ENTRY(jobject, JVM_ConstantPoolGetFieldAt(JNIEnv *env, jobject obj, jobject unusedl, jint index))2357{2358JVMWrapper("JVM_ConstantPoolGetFieldAt");2359JvmtiVMObjectAllocEventCollector oam;2360constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));2361bounds_check(cp, index, CHECK_NULL);2362jobject res = get_field_at_helper(cp, index, true, CHECK_NULL);2363return res;2364}2365JVM_END23662367JVM_ENTRY(jobject, JVM_ConstantPoolGetFieldAtIfLoaded(JNIEnv *env, jobject obj, jobject unused, jint index))2368{2369JVMWrapper("JVM_ConstantPoolGetFieldAtIfLoaded");2370JvmtiVMObjectAllocEventCollector oam;2371constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));2372bounds_check(cp, index, CHECK_NULL);2373jobject res = get_field_at_helper(cp, index, false, CHECK_NULL);2374return res;2375}2376JVM_END23772378JVM_ENTRY(jobjectArray, JVM_ConstantPoolGetMemberRefInfoAt(JNIEnv *env, jobject obj, jobject unused, jint index))2379{2380JVMWrapper("JVM_ConstantPoolGetMemberRefInfoAt");2381JvmtiVMObjectAllocEventCollector oam;2382constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));2383bounds_check(cp, index, CHECK_NULL);2384constantTag tag = cp->tag_at(index);2385if (!tag.is_field_or_method()) {2386THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");2387}2388int klass_ref = cp->uncached_klass_ref_index_at(index);2389Symbol* klass_name = cp->klass_name_at(klass_ref);2390Symbol* member_name = cp->uncached_name_ref_at(index);2391Symbol* member_sig = cp->uncached_signature_ref_at(index);2392objArrayOop dest_o = oopFactory::new_objArray(SystemDictionary::String_klass(), 3, CHECK_NULL);2393objArrayHandle dest(THREAD, dest_o);2394Handle str = java_lang_String::create_from_symbol(klass_name, CHECK_NULL);2395dest->obj_at_put(0, str());2396str = java_lang_String::create_from_symbol(member_name, CHECK_NULL);2397dest->obj_at_put(1, str());2398str = java_lang_String::create_from_symbol(member_sig, CHECK_NULL);2399dest->obj_at_put(2, str());2400return (jobjectArray) JNIHandles::make_local(dest());2401}2402JVM_END24032404JVM_ENTRY(jint, JVM_ConstantPoolGetIntAt(JNIEnv *env, jobject obj, jobject unused, jint index))2405{2406JVMWrapper("JVM_ConstantPoolGetIntAt");2407constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));2408bounds_check(cp, index, CHECK_0);2409constantTag tag = cp->tag_at(index);2410if (!tag.is_int()) {2411THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");2412}2413return cp->int_at(index);2414}2415JVM_END24162417JVM_ENTRY(jlong, JVM_ConstantPoolGetLongAt(JNIEnv *env, jobject obj, jobject unused, jint index))2418{2419JVMWrapper("JVM_ConstantPoolGetLongAt");2420constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));2421bounds_check(cp, index, CHECK_(0L));2422constantTag tag = cp->tag_at(index);2423if (!tag.is_long()) {2424THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");2425}2426return cp->long_at(index);2427}2428JVM_END24292430JVM_ENTRY(jfloat, JVM_ConstantPoolGetFloatAt(JNIEnv *env, jobject obj, jobject unused, jint index))2431{2432JVMWrapper("JVM_ConstantPoolGetFloatAt");2433constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));2434bounds_check(cp, index, CHECK_(0.0f));2435constantTag tag = cp->tag_at(index);2436if (!tag.is_float()) {2437THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");2438}2439return cp->float_at(index);2440}2441JVM_END24422443JVM_ENTRY(jdouble, JVM_ConstantPoolGetDoubleAt(JNIEnv *env, jobject obj, jobject unused, jint index))2444{2445JVMWrapper("JVM_ConstantPoolGetDoubleAt");2446constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));2447bounds_check(cp, index, CHECK_(0.0));2448constantTag tag = cp->tag_at(index);2449if (!tag.is_double()) {2450THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");2451}2452return cp->double_at(index);2453}2454JVM_END24552456JVM_ENTRY(jstring, JVM_ConstantPoolGetStringAt(JNIEnv *env, jobject obj, jobject unused, jint index))2457{2458JVMWrapper("JVM_ConstantPoolGetStringAt");2459constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));2460bounds_check(cp, index, CHECK_NULL);2461constantTag tag = cp->tag_at(index);2462if (!tag.is_string()) {2463THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");2464}2465oop str = cp->string_at(index, CHECK_NULL);2466return (jstring) JNIHandles::make_local(str);2467}2468JVM_END24692470JVM_ENTRY(jstring, JVM_ConstantPoolGetUTF8At(JNIEnv *env, jobject obj, jobject unused, jint index))2471{2472JVMWrapper("JVM_ConstantPoolGetUTF8At");2473JvmtiVMObjectAllocEventCollector oam;2474constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));2475bounds_check(cp, index, CHECK_NULL);2476constantTag tag = cp->tag_at(index);2477if (!tag.is_symbol()) {2478THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");2479}2480Symbol* sym = cp->symbol_at(index);2481Handle str = java_lang_String::create_from_symbol(sym, CHECK_NULL);2482return (jstring) JNIHandles::make_local(str());2483}2484JVM_END248524862487// Assertion support. //////////////////////////////////////////////////////////24882489JVM_ENTRY(jboolean, JVM_DesiredAssertionStatus(JNIEnv *env, jclass unused, jclass cls))2490JVMWrapper("JVM_DesiredAssertionStatus");2491assert(cls != NULL, "bad class");24922493oop r = JNIHandles::resolve(cls);2494assert(! java_lang_Class::is_primitive(r), "primitive classes not allowed");2495if (java_lang_Class::is_primitive(r)) return false;24962497Klass* k = java_lang_Class::as_Klass(r);2498assert(k->oop_is_instance(), "must be an instance klass");2499if (! k->oop_is_instance()) return false;25002501ResourceMark rm(THREAD);2502const char* name = k->name()->as_C_string();2503bool system_class = k->class_loader() == NULL;2504return JavaAssertions::enabled(name, system_class);25052506JVM_END250725082509// Return a new AssertionStatusDirectives object with the fields filled in with2510// command-line assertion arguments (i.e., -ea, -da).2511JVM_ENTRY(jobject, JVM_AssertionStatusDirectives(JNIEnv *env, jclass unused))2512JVMWrapper("JVM_AssertionStatusDirectives");2513JvmtiVMObjectAllocEventCollector oam;2514oop asd = JavaAssertions::createAssertionStatusDirectives(CHECK_NULL);2515return JNIHandles::make_local(env, asd);2516JVM_END25172518// Verification ////////////////////////////////////////////////////////////////////////////////25192520// Reflection for the verifier /////////////////////////////////////////////////////////////////25212522// RedefineClasses support: bug 6214132 caused verification to fail.2523// All functions from this section should call the jvmtiThreadSate function:2524// Klass* class_to_verify_considering_redefinition(Klass* klass).2525// The function returns a Klass* of the _scratch_class if the verifier2526// was invoked in the middle of the class redefinition.2527// Otherwise it returns its argument value which is the _the_class Klass*.2528// Please, refer to the description in the jvmtiThreadSate.hpp.25292530JVM_ENTRY(const char*, JVM_GetClassNameUTF(JNIEnv *env, jclass cls))2531JVMWrapper("JVM_GetClassNameUTF");2532Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));2533k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);2534return k->name()->as_utf8();2535JVM_END253625372538JVM_QUICK_ENTRY(void, JVM_GetClassCPTypes(JNIEnv *env, jclass cls, unsigned char *types))2539JVMWrapper("JVM_GetClassCPTypes");2540Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));2541k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);2542// types will have length zero if this is not an InstanceKlass2543// (length is determined by call to JVM_GetClassCPEntriesCount)2544if (k->oop_is_instance()) {2545ConstantPool* cp = InstanceKlass::cast(k)->constants();2546for (int index = cp->length() - 1; index >= 0; index--) {2547constantTag tag = cp->tag_at(index);2548types[index] = (tag.is_unresolved_klass()) ? JVM_CONSTANT_Class : tag.value();2549}2550}2551JVM_END255225532554JVM_QUICK_ENTRY(jint, JVM_GetClassCPEntriesCount(JNIEnv *env, jclass cls))2555JVMWrapper("JVM_GetClassCPEntriesCount");2556Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));2557k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);2558if (!k->oop_is_instance())2559return 0;2560return InstanceKlass::cast(k)->constants()->length();2561JVM_END256225632564JVM_QUICK_ENTRY(jint, JVM_GetClassFieldsCount(JNIEnv *env, jclass cls))2565JVMWrapper("JVM_GetClassFieldsCount");2566Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));2567k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);2568if (!k->oop_is_instance())2569return 0;2570return InstanceKlass::cast(k)->java_fields_count();2571JVM_END257225732574JVM_QUICK_ENTRY(jint, JVM_GetClassMethodsCount(JNIEnv *env, jclass cls))2575JVMWrapper("JVM_GetClassMethodsCount");2576Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));2577k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);2578if (!k->oop_is_instance())2579return 0;2580return InstanceKlass::cast(k)->methods()->length();2581JVM_END258225832584// The following methods, used for the verifier, are never called with2585// array klasses, so a direct cast to InstanceKlass is safe.2586// Typically, these methods are called in a loop with bounds determined2587// by the results of JVM_GetClass{Fields,Methods}Count, which return2588// zero for arrays.2589JVM_QUICK_ENTRY(void, JVM_GetMethodIxExceptionIndexes(JNIEnv *env, jclass cls, jint method_index, unsigned short *exceptions))2590JVMWrapper("JVM_GetMethodIxExceptionIndexes");2591Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));2592k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);2593Method* method = InstanceKlass::cast(k)->methods()->at(method_index);2594int length = method->checked_exceptions_length();2595if (length > 0) {2596CheckedExceptionElement* table= method->checked_exceptions_start();2597for (int i = 0; i < length; i++) {2598exceptions[i] = table[i].class_cp_index;2599}2600}2601JVM_END260226032604JVM_QUICK_ENTRY(jint, JVM_GetMethodIxExceptionsCount(JNIEnv *env, jclass cls, jint method_index))2605JVMWrapper("JVM_GetMethodIxExceptionsCount");2606Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));2607k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);2608Method* method = InstanceKlass::cast(k)->methods()->at(method_index);2609return method->checked_exceptions_length();2610JVM_END261126122613JVM_QUICK_ENTRY(void, JVM_GetMethodIxByteCode(JNIEnv *env, jclass cls, jint method_index, unsigned char *code))2614JVMWrapper("JVM_GetMethodIxByteCode");2615Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));2616k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);2617Method* method = InstanceKlass::cast(k)->methods()->at(method_index);2618memcpy(code, method->code_base(), method->code_size());2619JVM_END262026212622JVM_QUICK_ENTRY(jint, JVM_GetMethodIxByteCodeLength(JNIEnv *env, jclass cls, jint method_index))2623JVMWrapper("JVM_GetMethodIxByteCodeLength");2624Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));2625k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);2626Method* method = InstanceKlass::cast(k)->methods()->at(method_index);2627return method->code_size();2628JVM_END262926302631JVM_QUICK_ENTRY(void, JVM_GetMethodIxExceptionTableEntry(JNIEnv *env, jclass cls, jint method_index, jint entry_index, JVM_ExceptionTableEntryType *entry))2632JVMWrapper("JVM_GetMethodIxExceptionTableEntry");2633Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));2634k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);2635Method* method = InstanceKlass::cast(k)->methods()->at(method_index);2636ExceptionTable extable(method);2637entry->start_pc = extable.start_pc(entry_index);2638entry->end_pc = extable.end_pc(entry_index);2639entry->handler_pc = extable.handler_pc(entry_index);2640entry->catchType = extable.catch_type_index(entry_index);2641JVM_END264226432644JVM_QUICK_ENTRY(jint, JVM_GetMethodIxExceptionTableLength(JNIEnv *env, jclass cls, int method_index))2645JVMWrapper("JVM_GetMethodIxExceptionTableLength");2646Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));2647k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);2648Method* method = InstanceKlass::cast(k)->methods()->at(method_index);2649return method->exception_table_length();2650JVM_END265126522653JVM_QUICK_ENTRY(jint, JVM_GetMethodIxModifiers(JNIEnv *env, jclass cls, int method_index))2654JVMWrapper("JVM_GetMethodIxModifiers");2655Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));2656k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);2657Method* method = InstanceKlass::cast(k)->methods()->at(method_index);2658return method->access_flags().as_int() & JVM_RECOGNIZED_METHOD_MODIFIERS;2659JVM_END266026612662JVM_QUICK_ENTRY(jint, JVM_GetFieldIxModifiers(JNIEnv *env, jclass cls, int field_index))2663JVMWrapper("JVM_GetFieldIxModifiers");2664Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));2665k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);2666return InstanceKlass::cast(k)->field_access_flags(field_index) & JVM_RECOGNIZED_FIELD_MODIFIERS;2667JVM_END266826692670JVM_QUICK_ENTRY(jint, JVM_GetMethodIxLocalsCount(JNIEnv *env, jclass cls, int method_index))2671JVMWrapper("JVM_GetMethodIxLocalsCount");2672Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));2673k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);2674Method* method = InstanceKlass::cast(k)->methods()->at(method_index);2675return method->max_locals();2676JVM_END267726782679JVM_QUICK_ENTRY(jint, JVM_GetMethodIxArgsSize(JNIEnv *env, jclass cls, int method_index))2680JVMWrapper("JVM_GetMethodIxArgsSize");2681Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));2682k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);2683Method* method = InstanceKlass::cast(k)->methods()->at(method_index);2684return method->size_of_parameters();2685JVM_END268626872688JVM_QUICK_ENTRY(jint, JVM_GetMethodIxMaxStack(JNIEnv *env, jclass cls, int method_index))2689JVMWrapper("JVM_GetMethodIxMaxStack");2690Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));2691k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);2692Method* method = InstanceKlass::cast(k)->methods()->at(method_index);2693return method->verifier_max_stack();2694JVM_END269526962697JVM_QUICK_ENTRY(jboolean, JVM_IsConstructorIx(JNIEnv *env, jclass cls, int method_index))2698JVMWrapper("JVM_IsConstructorIx");2699ResourceMark rm(THREAD);2700Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));2701k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);2702Method* method = InstanceKlass::cast(k)->methods()->at(method_index);2703return method->name() == vmSymbols::object_initializer_name();2704JVM_END270527062707JVM_QUICK_ENTRY(jboolean, JVM_IsVMGeneratedMethodIx(JNIEnv *env, jclass cls, int method_index))2708JVMWrapper("JVM_IsVMGeneratedMethodIx");2709ResourceMark rm(THREAD);2710Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));2711k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);2712Method* method = InstanceKlass::cast(k)->methods()->at(method_index);2713return method->is_overpass();2714JVM_END27152716JVM_ENTRY(const char*, JVM_GetMethodIxNameUTF(JNIEnv *env, jclass cls, jint method_index))2717JVMWrapper("JVM_GetMethodIxIxUTF");2718Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));2719k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);2720Method* method = InstanceKlass::cast(k)->methods()->at(method_index);2721return method->name()->as_utf8();2722JVM_END272327242725JVM_ENTRY(const char*, JVM_GetMethodIxSignatureUTF(JNIEnv *env, jclass cls, jint method_index))2726JVMWrapper("JVM_GetMethodIxSignatureUTF");2727Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));2728k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);2729Method* method = InstanceKlass::cast(k)->methods()->at(method_index);2730return method->signature()->as_utf8();2731JVM_END27322733/**2734* All of these JVM_GetCP-xxx methods are used by the old verifier to2735* read entries in the constant pool. Since the old verifier always2736* works on a copy of the code, it will not see any rewriting that2737* may possibly occur in the middle of verification. So it is important2738* that nothing it calls tries to use the cpCache instead of the raw2739* constant pool, so we must use cp->uncached_x methods when appropriate.2740*/2741JVM_ENTRY(const char*, JVM_GetCPFieldNameUTF(JNIEnv *env, jclass cls, jint cp_index))2742JVMWrapper("JVM_GetCPFieldNameUTF");2743Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));2744k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);2745ConstantPool* cp = InstanceKlass::cast(k)->constants();2746switch (cp->tag_at(cp_index).value()) {2747case JVM_CONSTANT_Fieldref:2748return cp->uncached_name_ref_at(cp_index)->as_utf8();2749default:2750fatal("JVM_GetCPFieldNameUTF: illegal constant");2751}2752ShouldNotReachHere();2753return NULL;2754JVM_END275527562757JVM_ENTRY(const char*, JVM_GetCPMethodNameUTF(JNIEnv *env, jclass cls, jint cp_index))2758JVMWrapper("JVM_GetCPMethodNameUTF");2759Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));2760k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);2761ConstantPool* cp = InstanceKlass::cast(k)->constants();2762switch (cp->tag_at(cp_index).value()) {2763case JVM_CONSTANT_InterfaceMethodref:2764case JVM_CONSTANT_Methodref:2765return cp->uncached_name_ref_at(cp_index)->as_utf8();2766default:2767fatal("JVM_GetCPMethodNameUTF: illegal constant");2768}2769ShouldNotReachHere();2770return NULL;2771JVM_END277227732774JVM_ENTRY(const char*, JVM_GetCPMethodSignatureUTF(JNIEnv *env, jclass cls, jint cp_index))2775JVMWrapper("JVM_GetCPMethodSignatureUTF");2776Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));2777k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);2778ConstantPool* cp = InstanceKlass::cast(k)->constants();2779switch (cp->tag_at(cp_index).value()) {2780case JVM_CONSTANT_InterfaceMethodref:2781case JVM_CONSTANT_Methodref:2782return cp->uncached_signature_ref_at(cp_index)->as_utf8();2783default:2784fatal("JVM_GetCPMethodSignatureUTF: illegal constant");2785}2786ShouldNotReachHere();2787return NULL;2788JVM_END278927902791JVM_ENTRY(const char*, JVM_GetCPFieldSignatureUTF(JNIEnv *env, jclass cls, jint cp_index))2792JVMWrapper("JVM_GetCPFieldSignatureUTF");2793Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));2794k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);2795ConstantPool* cp = InstanceKlass::cast(k)->constants();2796switch (cp->tag_at(cp_index).value()) {2797case JVM_CONSTANT_Fieldref:2798return cp->uncached_signature_ref_at(cp_index)->as_utf8();2799default:2800fatal("JVM_GetCPFieldSignatureUTF: illegal constant");2801}2802ShouldNotReachHere();2803return NULL;2804JVM_END280528062807JVM_ENTRY(const char*, JVM_GetCPClassNameUTF(JNIEnv *env, jclass cls, jint cp_index))2808JVMWrapper("JVM_GetCPClassNameUTF");2809Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));2810k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);2811ConstantPool* cp = InstanceKlass::cast(k)->constants();2812Symbol* classname = cp->klass_name_at(cp_index);2813return classname->as_utf8();2814JVM_END281528162817JVM_ENTRY(const char*, JVM_GetCPFieldClassNameUTF(JNIEnv *env, jclass cls, jint cp_index))2818JVMWrapper("JVM_GetCPFieldClassNameUTF");2819Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));2820k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);2821ConstantPool* cp = InstanceKlass::cast(k)->constants();2822switch (cp->tag_at(cp_index).value()) {2823case JVM_CONSTANT_Fieldref: {2824int class_index = cp->uncached_klass_ref_index_at(cp_index);2825Symbol* classname = cp->klass_name_at(class_index);2826return classname->as_utf8();2827}2828default:2829fatal("JVM_GetCPFieldClassNameUTF: illegal constant");2830}2831ShouldNotReachHere();2832return NULL;2833JVM_END283428352836JVM_ENTRY(const char*, JVM_GetCPMethodClassNameUTF(JNIEnv *env, jclass cls, jint cp_index))2837JVMWrapper("JVM_GetCPMethodClassNameUTF");2838Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));2839k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);2840ConstantPool* cp = InstanceKlass::cast(k)->constants();2841switch (cp->tag_at(cp_index).value()) {2842case JVM_CONSTANT_Methodref:2843case JVM_CONSTANT_InterfaceMethodref: {2844int class_index = cp->uncached_klass_ref_index_at(cp_index);2845Symbol* classname = cp->klass_name_at(class_index);2846return classname->as_utf8();2847}2848default:2849fatal("JVM_GetCPMethodClassNameUTF: illegal constant");2850}2851ShouldNotReachHere();2852return NULL;2853JVM_END285428552856JVM_ENTRY(jint, JVM_GetCPFieldModifiers(JNIEnv *env, jclass cls, int cp_index, jclass called_cls))2857JVMWrapper("JVM_GetCPFieldModifiers");2858Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));2859Klass* k_called = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(called_cls));2860k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);2861k_called = JvmtiThreadState::class_to_verify_considering_redefinition(k_called, thread);2862ConstantPool* cp = InstanceKlass::cast(k)->constants();2863ConstantPool* cp_called = InstanceKlass::cast(k_called)->constants();2864switch (cp->tag_at(cp_index).value()) {2865case JVM_CONSTANT_Fieldref: {2866Symbol* name = cp->uncached_name_ref_at(cp_index);2867Symbol* signature = cp->uncached_signature_ref_at(cp_index);2868for (JavaFieldStream fs(k_called); !fs.done(); fs.next()) {2869if (fs.name() == name && fs.signature() == signature) {2870return fs.access_flags().as_short() & JVM_RECOGNIZED_FIELD_MODIFIERS;2871}2872}2873return -1;2874}2875default:2876fatal("JVM_GetCPFieldModifiers: illegal constant");2877}2878ShouldNotReachHere();2879return 0;2880JVM_END288128822883JVM_QUICK_ENTRY(jint, JVM_GetCPMethodModifiers(JNIEnv *env, jclass cls, int cp_index, jclass called_cls))2884JVMWrapper("JVM_GetCPMethodModifiers");2885Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));2886Klass* k_called = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(called_cls));2887k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);2888k_called = JvmtiThreadState::class_to_verify_considering_redefinition(k_called, thread);2889ConstantPool* cp = InstanceKlass::cast(k)->constants();2890switch (cp->tag_at(cp_index).value()) {2891case JVM_CONSTANT_Methodref:2892case JVM_CONSTANT_InterfaceMethodref: {2893Symbol* name = cp->uncached_name_ref_at(cp_index);2894Symbol* signature = cp->uncached_signature_ref_at(cp_index);2895Array<Method*>* methods = InstanceKlass::cast(k_called)->methods();2896int methods_count = methods->length();2897for (int i = 0; i < methods_count; i++) {2898Method* method = methods->at(i);2899if (method->name() == name && method->signature() == signature) {2900return method->access_flags().as_int() & JVM_RECOGNIZED_METHOD_MODIFIERS;2901}2902}2903return -1;2904}2905default:2906fatal("JVM_GetCPMethodModifiers: illegal constant");2907}2908ShouldNotReachHere();2909return 0;2910JVM_END291129122913// Misc //////////////////////////////////////////////////////////////////////////////////////////////29142915JVM_LEAF(void, JVM_ReleaseUTF(const char *utf))2916// So long as UTF8::convert_to_utf8 returns resource strings, we don't have to do anything2917JVM_END291829192920JVM_ENTRY(jboolean, JVM_IsSameClassPackage(JNIEnv *env, jclass class1, jclass class2))2921JVMWrapper("JVM_IsSameClassPackage");2922oop class1_mirror = JNIHandles::resolve_non_null(class1);2923oop class2_mirror = JNIHandles::resolve_non_null(class2);2924Klass* klass1 = java_lang_Class::as_Klass(class1_mirror);2925Klass* klass2 = java_lang_Class::as_Klass(class2_mirror);2926return (jboolean) Reflection::is_same_class_package(klass1, klass2);2927JVM_END292829292930// IO functions ////////////////////////////////////////////////////////////////////////////////////////29312932JVM_LEAF(jint, JVM_Open(const char *fname, jint flags, jint mode))2933JVMWrapper2("JVM_Open (%s)", fname);29342935//%note jvm_r62936int result = os::open(fname, flags, mode);2937if (result >= 0) {2938return result;2939} else {2940switch(errno) {2941case EEXIST:2942return JVM_EEXIST;2943default:2944return -1;2945}2946}2947JVM_END294829492950JVM_LEAF(jint, JVM_Close(jint fd))2951JVMWrapper2("JVM_Close (0x%x)", fd);2952//%note jvm_r62953return os::close(fd);2954JVM_END295529562957JVM_LEAF(jint, JVM_Read(jint fd, char *buf, jint nbytes))2958JVMWrapper2("JVM_Read (0x%x)", fd);29592960//%note jvm_r62961return (jint)os::restartable_read(fd, buf, nbytes);2962JVM_END296329642965JVM_LEAF(jint, JVM_Write(jint fd, char *buf, jint nbytes))2966JVMWrapper2("JVM_Write (0x%x)", fd);29672968//%note jvm_r62969return (jint)os::write(fd, buf, nbytes);2970JVM_END297129722973JVM_LEAF(jint, JVM_Available(jint fd, jlong *pbytes))2974JVMWrapper2("JVM_Available (0x%x)", fd);2975//%note jvm_r62976return os::available(fd, pbytes);2977JVM_END297829792980JVM_LEAF(jlong, JVM_Lseek(jint fd, jlong offset, jint whence))2981JVMWrapper4("JVM_Lseek (0x%x, " INT64_FORMAT ", %d)", fd, (int64_t) offset, whence);2982//%note jvm_r62983return os::lseek(fd, offset, whence);2984JVM_END298529862987JVM_LEAF(jint, JVM_SetLength(jint fd, jlong length))2988JVMWrapper3("JVM_SetLength (0x%x, " INT64_FORMAT ")", fd, (int64_t) length);2989return os::ftruncate(fd, length);2990JVM_END299129922993JVM_LEAF(jint, JVM_Sync(jint fd))2994JVMWrapper2("JVM_Sync (0x%x)", fd);2995//%note jvm_r62996return os::fsync(fd);2997JVM_END299829993000// Printing support //////////////////////////////////////////////////3001extern "C" {30023003ATTRIBUTE_PRINTF(3, 0)3004int jio_vsnprintf(char *str, size_t count, const char *fmt, va_list args) {3005// Reject count values that are negative signed values converted to3006// unsigned; see bug 4399518, 44172143007if ((intptr_t)count <= 0) return -1;30083009int result = os::vsnprintf(str, count, fmt, args);3010if (result > 0 && (size_t)result >= count) {3011result = -1;3012}30133014return result;3015}30163017ATTRIBUTE_PRINTF(3, 0)3018int jio_snprintf(char *str, size_t count, const char *fmt, ...) {3019va_list args;3020int len;3021va_start(args, fmt);3022len = jio_vsnprintf(str, count, fmt, args);3023va_end(args);3024return len;3025}30263027ATTRIBUTE_PRINTF(2,3)3028int jio_fprintf(FILE* f, const char *fmt, ...) {3029int len;3030va_list args;3031va_start(args, fmt);3032len = jio_vfprintf(f, fmt, args);3033va_end(args);3034return len;3035}30363037ATTRIBUTE_PRINTF(2, 0)3038int jio_vfprintf(FILE* f, const char *fmt, va_list args) {3039if (Arguments::vfprintf_hook() != NULL) {3040return Arguments::vfprintf_hook()(f, fmt, args);3041} else {3042return vfprintf(f, fmt, args);3043}3044}30453046ATTRIBUTE_PRINTF(1, 2)3047JNIEXPORT int jio_printf(const char *fmt, ...) {3048int len;3049va_list args;3050va_start(args, fmt);3051len = jio_vfprintf(defaultStream::output_stream(), fmt, args);3052va_end(args);3053return len;3054}305530563057// HotSpot specific jio method3058void jio_print(const char* s) {3059// Try to make this function as atomic as possible.3060if (Arguments::vfprintf_hook() != NULL) {3061jio_fprintf(defaultStream::output_stream(), "%s", s);3062} else {3063// Make an unused local variable to avoid warning from gcc 4.x compiler.3064size_t count = ::write(defaultStream::output_fd(), s, (int)strlen(s));3065}3066}30673068} // Extern C30693070// java.lang.Thread //////////////////////////////////////////////////////////////////////////////30713072// In most of the JVM Thread support functions we need to be sure to lock the Threads_lock3073// to prevent the target thread from exiting after we have a pointer to the C++ Thread or3074// OSThread objects. The exception to this rule is when the target object is the thread3075// doing the operation, in which case we know that the thread won't exit until the3076// operation is done (all exits being voluntary). There are a few cases where it is3077// rather silly to do operations on yourself, like resuming yourself or asking whether3078// you are alive. While these can still happen, they are not subject to deadlocks if3079// the lock is held while the operation occurs (this is not the case for suspend, for3080// instance), and are very unlikely. Because IsAlive needs to be fast and its3081// implementation is local to this file, we always lock Threads_lock for that one.30823083static void thread_entry(JavaThread* thread, TRAPS) {3084HandleMark hm(THREAD);3085Handle obj(THREAD, thread->threadObj());3086JavaValue result(T_VOID);3087JavaCalls::call_virtual(&result,3088obj,3089KlassHandle(THREAD, SystemDictionary::Thread_klass()),3090vmSymbols::run_method_name(),3091vmSymbols::void_method_signature(),3092THREAD);3093}309430953096JVM_ENTRY(void, JVM_StartThread(JNIEnv* env, jobject jthread))3097JVMWrapper("JVM_StartThread");3098JavaThread *native_thread = NULL;30993100// We cannot hold the Threads_lock when we throw an exception,3101// due to rank ordering issues. Example: we might need to grab the3102// Heap_lock while we construct the exception.3103bool throw_illegal_thread_state = false;31043105// We must release the Threads_lock before we can post a jvmti event3106// in Thread::start.3107{3108// Ensure that the C++ Thread and OSThread structures aren't freed before3109// we operate.3110MutexLocker mu(Threads_lock);31113112// Since JDK 5 the java.lang.Thread threadStatus is used to prevent3113// re-starting an already started thread, so we should usually find3114// that the JavaThread is null. However for a JNI attached thread3115// there is a small window between the Thread object being created3116// (with its JavaThread set) and the update to its threadStatus, so we3117// have to check for this3118if (java_lang_Thread::thread(JNIHandles::resolve_non_null(jthread)) != NULL) {3119throw_illegal_thread_state = true;3120} else {3121// We could also check the stillborn flag to see if this thread was already stopped, but3122// for historical reasons we let the thread detect that itself when it starts running31233124jlong size =3125java_lang_Thread::stackSize(JNIHandles::resolve_non_null(jthread));3126// Allocate the C++ Thread structure and create the native thread. The3127// stack size retrieved from java is signed, but the constructor takes3128// size_t (an unsigned type), so avoid passing negative values which would3129// result in really large stacks.3130size_t sz = size > 0 ? (size_t) size : 0;3131native_thread = new JavaThread(&thread_entry, sz);31323133// At this point it may be possible that no osthread was created for the3134// JavaThread due to lack of memory. Check for this situation and throw3135// an exception if necessary. Eventually we may want to change this so3136// that we only grab the lock if the thread was created successfully -3137// then we can also do this check and throw the exception in the3138// JavaThread constructor.3139if (native_thread->osthread() != NULL) {3140// Note: the current thread is not being used within "prepare".3141native_thread->prepare(jthread);3142}3143}3144}31453146if (throw_illegal_thread_state) {3147THROW(vmSymbols::java_lang_IllegalThreadStateException());3148}31493150assert(native_thread != NULL, "Starting null thread?");31513152if (native_thread->osthread() == NULL) {3153// No one should hold a reference to the 'native_thread'.3154delete native_thread;3155if (JvmtiExport::should_post_resource_exhausted()) {3156JvmtiExport::post_resource_exhausted(3157JVMTI_RESOURCE_EXHAUSTED_OOM_ERROR | JVMTI_RESOURCE_EXHAUSTED_THREADS,3158"unable to create new native thread");3159}3160THROW_MSG(vmSymbols::java_lang_OutOfMemoryError(),3161"unable to create new native thread");3162}31633164Thread::start(native_thread);31653166JVM_END31673168// JVM_Stop is implemented using a VM_Operation, so threads are forced to safepoints3169// before the quasi-asynchronous exception is delivered. This is a little obtrusive,3170// but is thought to be reliable and simple. In the case, where the receiver is the3171// same thread as the sender, no safepoint is needed.3172JVM_ENTRY(void, JVM_StopThread(JNIEnv* env, jobject jthread, jobject throwable))3173JVMWrapper("JVM_StopThread");31743175oop java_throwable = JNIHandles::resolve(throwable);3176if (java_throwable == NULL) {3177THROW(vmSymbols::java_lang_NullPointerException());3178}3179oop java_thread = JNIHandles::resolve_non_null(jthread);3180JavaThread* receiver = java_lang_Thread::thread(java_thread);3181Events::log_exception(JavaThread::current(),3182"JVM_StopThread thread JavaThread " INTPTR_FORMAT " as oop " INTPTR_FORMAT " [exception " INTPTR_FORMAT "]",3183p2i(receiver), p2i((address)java_thread), p2i(throwable));3184// First check if thread is alive3185if (receiver != NULL) {3186// Check if exception is getting thrown at self (use oop equality, since the3187// target object might exit)3188if (java_thread == thread->threadObj()) {3189THROW_OOP(java_throwable);3190} else {3191// Enques a VM_Operation to stop all threads and then deliver the exception...3192Thread::send_async_exception(java_thread, JNIHandles::resolve(throwable));3193}3194}3195else {3196// Either:3197// - target thread has not been started before being stopped, or3198// - target thread already terminated3199// We could read the threadStatus to determine which case it is3200// but that is overkill as it doesn't matter. We must set the3201// stillborn flag for the first case, and if the thread has already3202// exited setting this flag has no affect3203java_lang_Thread::set_stillborn(java_thread);3204}3205JVM_END320632073208JVM_ENTRY(jboolean, JVM_IsThreadAlive(JNIEnv* env, jobject jthread))3209JVMWrapper("JVM_IsThreadAlive");32103211oop thread_oop = JNIHandles::resolve_non_null(jthread);3212return java_lang_Thread::is_alive(thread_oop);3213JVM_END321432153216JVM_ENTRY(void, JVM_SuspendThread(JNIEnv* env, jobject jthread))3217JVMWrapper("JVM_SuspendThread");3218oop java_thread = JNIHandles::resolve_non_null(jthread);3219JavaThread* receiver = java_lang_Thread::thread(java_thread);32203221if (receiver != NULL) {3222// thread has run and has not exited (still on threads list)32233224{3225MutexLockerEx ml(receiver->SR_lock(), Mutex::_no_safepoint_check_flag);3226if (receiver->is_external_suspend()) {3227// Don't allow nested external suspend requests. We can't return3228// an error from this interface so just ignore the problem.3229return;3230}3231if (receiver->is_exiting()) { // thread is in the process of exiting3232return;3233}3234receiver->set_external_suspend();3235}32363237// java_suspend() will catch threads in the process of exiting3238// and will ignore them.3239receiver->java_suspend();32403241// It would be nice to have the following assertion in all the3242// time, but it is possible for a racing resume request to have3243// resumed this thread right after we suspended it. Temporarily3244// enable this assertion if you are chasing a different kind of3245// bug.3246//3247// assert(java_lang_Thread::thread(receiver->threadObj()) == NULL ||3248// receiver->is_being_ext_suspended(), "thread is not suspended");3249}3250JVM_END325132523253JVM_ENTRY(void, JVM_ResumeThread(JNIEnv* env, jobject jthread))3254JVMWrapper("JVM_ResumeThread");3255// Ensure that the C++ Thread and OSThread structures aren't freed before we operate.3256// We need to *always* get the threads lock here, since this operation cannot be allowed during3257// a safepoint. The safepoint code relies on suspending a thread to examine its state. If other3258// threads randomly resumes threads, then a thread might not be suspended when the safepoint code3259// looks at it.3260MutexLocker ml(Threads_lock);3261JavaThread* thr = java_lang_Thread::thread(JNIHandles::resolve_non_null(jthread));3262if (thr != NULL) {3263// the thread has run and is not in the process of exiting3264thr->java_resume();3265}3266JVM_END326732683269JVM_ENTRY(void, JVM_SetThreadPriority(JNIEnv* env, jobject jthread, jint prio))3270JVMWrapper("JVM_SetThreadPriority");3271// Ensure that the C++ Thread and OSThread structures aren't freed before we operate3272MutexLocker ml(Threads_lock);3273oop java_thread = JNIHandles::resolve_non_null(jthread);3274java_lang_Thread::set_priority(java_thread, (ThreadPriority)prio);3275JavaThread* thr = java_lang_Thread::thread(java_thread);3276if (thr != NULL) { // Thread not yet started; priority pushed down when it is3277Thread::set_priority(thr, (ThreadPriority)prio);3278}3279JVM_END328032813282JVM_ENTRY(void, JVM_Yield(JNIEnv *env, jclass threadClass))3283JVMWrapper("JVM_Yield");3284if (os::dont_yield()) return;3285#ifndef USDT23286HS_DTRACE_PROBE0(hotspot, thread__yield);3287#else /* USDT2 */3288HOTSPOT_THREAD_YIELD();3289#endif /* USDT2 */3290// When ConvertYieldToSleep is off (default), this matches the classic VM use of yield.3291// Critical for similar threading behaviour3292if (ConvertYieldToSleep) {3293os::sleep(thread, MinSleepInterval, false);3294} else {3295os::yield();3296}3297JVM_END32983299static void post_thread_sleep_event(EventThreadSleep* event, jlong millis) {3300assert(event != NULL, "invariant");3301assert(event->should_commit(), "invariant");3302event->set_time(millis);3303event->commit();3304}33053306JVM_ENTRY(void, JVM_Sleep(JNIEnv* env, jclass threadClass, jlong millis))3307JVMWrapper("JVM_Sleep");33083309if (millis < 0) {3310THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "timeout value is negative");3311}33123313if (Thread::is_interrupted (THREAD, true) && !HAS_PENDING_EXCEPTION) {3314THROW_MSG(vmSymbols::java_lang_InterruptedException(), "sleep interrupted");3315}33163317// Save current thread state and restore it at the end of this block.3318// And set new thread state to SLEEPING.3319JavaThreadSleepState jtss(thread);33203321#ifndef USDT23322HS_DTRACE_PROBE1(hotspot, thread__sleep__begin, millis);3323#else /* USDT2 */3324HOTSPOT_THREAD_SLEEP_BEGIN(3325millis);3326#endif /* USDT2 */33273328EventThreadSleep event;33293330if (millis == 0) {3331// When ConvertSleepToYield is on, this matches the classic VM implementation of3332// JVM_Sleep. Critical for similar threading behaviour (Win32)3333// It appears that in certain GUI contexts, it may be beneficial to do a short sleep3334// for SOLARIS3335if (ConvertSleepToYield) {3336os::yield();3337} else {3338ThreadState old_state = thread->osthread()->get_state();3339thread->osthread()->set_state(SLEEPING);3340os::sleep(thread, MinSleepInterval, false);3341thread->osthread()->set_state(old_state);3342}3343} else {3344ThreadState old_state = thread->osthread()->get_state();3345thread->osthread()->set_state(SLEEPING);3346if (os::sleep(thread, millis, true) == OS_INTRPT) {3347// An asynchronous exception (e.g., ThreadDeathException) could have been thrown on3348// us while we were sleeping. We do not overwrite those.3349if (!HAS_PENDING_EXCEPTION) {3350if (event.should_commit()) {3351post_thread_sleep_event(&event, millis);3352}3353#ifndef USDT23354HS_DTRACE_PROBE1(hotspot, thread__sleep__end,1);3355#else /* USDT2 */3356HOTSPOT_THREAD_SLEEP_END(33571);3358#endif /* USDT2 */3359// TODO-FIXME: THROW_MSG returns which means we will not call set_state()3360// to properly restore the thread state. That's likely wrong.3361THROW_MSG(vmSymbols::java_lang_InterruptedException(), "sleep interrupted");3362}3363}3364thread->osthread()->set_state(old_state);3365}3366if (event.should_commit()) {3367post_thread_sleep_event(&event, millis);3368}3369#ifndef USDT23370HS_DTRACE_PROBE1(hotspot, thread__sleep__end,0);3371#else /* USDT2 */3372HOTSPOT_THREAD_SLEEP_END(33730);3374#endif /* USDT2 */3375JVM_END33763377JVM_ENTRY(jobject, JVM_CurrentThread(JNIEnv* env, jclass threadClass))3378JVMWrapper("JVM_CurrentThread");3379oop jthread = thread->threadObj();3380assert (thread != NULL, "no current thread!");3381return JNIHandles::make_local(env, jthread);3382JVM_END338333843385JVM_ENTRY(jint, JVM_CountStackFrames(JNIEnv* env, jobject jthread))3386JVMWrapper("JVM_CountStackFrames");33873388// Ensure that the C++ Thread and OSThread structures aren't freed before we operate3389oop java_thread = JNIHandles::resolve_non_null(jthread);3390bool throw_illegal_thread_state = false;3391int count = 0;33923393{3394MutexLockerEx ml(thread->threadObj() == java_thread ? NULL : Threads_lock);3395// We need to re-resolve the java_thread, since a GC might have happened during the3396// acquire of the lock3397JavaThread* thr = java_lang_Thread::thread(JNIHandles::resolve_non_null(jthread));33983399if (thr == NULL) {3400// do nothing3401} else if(! thr->is_external_suspend() || ! thr->frame_anchor()->walkable()) {3402// Check whether this java thread has been suspended already. If not, throws3403// IllegalThreadStateException. We defer to throw that exception until3404// Threads_lock is released since loading exception class has to leave VM.3405// The correct way to test a thread is actually suspended is3406// wait_for_ext_suspend_completion(), but we can't call that while holding3407// the Threads_lock. The above tests are sufficient for our purposes3408// provided the walkability of the stack is stable - which it isn't3409// 100% but close enough for most practical purposes.3410throw_illegal_thread_state = true;3411} else {3412// Count all java activation, i.e., number of vframes3413for(vframeStream vfst(thr); !vfst.at_end(); vfst.next()) {3414// Native frames are not counted3415if (!vfst.method()->is_native()) count++;3416}3417}3418}34193420if (throw_illegal_thread_state) {3421THROW_MSG_0(vmSymbols::java_lang_IllegalThreadStateException(),3422"this thread is not suspended");3423}3424return count;3425JVM_END34263427// Consider: A better way to implement JVM_Interrupt() is to acquire3428// Threads_lock to resolve the jthread into a Thread pointer, fetch3429// Thread->platformevent, Thread->native_thr, Thread->parker, etc.,3430// drop Threads_lock, and the perform the unpark() and thr_kill() operations3431// outside the critical section. Threads_lock is hot so we want to minimize3432// the hold-time. A cleaner interface would be to decompose interrupt into3433// two steps. The 1st phase, performed under Threads_lock, would return3434// a closure that'd be invoked after Threads_lock was dropped.3435// This tactic is safe as PlatformEvent and Parkers are type-stable (TSM) and3436// admit spurious wakeups.34373438JVM_ENTRY(void, JVM_Interrupt(JNIEnv* env, jobject jthread))3439JVMWrapper("JVM_Interrupt");34403441// Ensure that the C++ Thread and OSThread structures aren't freed before we operate3442oop java_thread = JNIHandles::resolve_non_null(jthread);3443MutexLockerEx ml(thread->threadObj() == java_thread ? NULL : Threads_lock);3444// We need to re-resolve the java_thread, since a GC might have happened during the3445// acquire of the lock3446JavaThread* thr = java_lang_Thread::thread(JNIHandles::resolve_non_null(jthread));3447if (thr != NULL) {3448Thread::interrupt(thr);3449}3450JVM_END345134523453JVM_QUICK_ENTRY(jboolean, JVM_IsInterrupted(JNIEnv* env, jobject jthread, jboolean clear_interrupted))3454JVMWrapper("JVM_IsInterrupted");34553456// Ensure that the C++ Thread and OSThread structures aren't freed before we operate3457oop java_thread = JNIHandles::resolve_non_null(jthread);3458MutexLockerEx ml(thread->threadObj() == java_thread ? NULL : Threads_lock);3459// We need to re-resolve the java_thread, since a GC might have happened during the3460// acquire of the lock3461JavaThread* thr = java_lang_Thread::thread(JNIHandles::resolve_non_null(jthread));3462if (thr == NULL) {3463return JNI_FALSE;3464} else {3465return (jboolean) Thread::is_interrupted(thr, clear_interrupted != 0);3466}3467JVM_END346834693470// Return true iff the current thread has locked the object passed in34713472JVM_ENTRY(jboolean, JVM_HoldsLock(JNIEnv* env, jclass threadClass, jobject obj))3473JVMWrapper("JVM_HoldsLock");3474assert(THREAD->is_Java_thread(), "sanity check");3475if (obj == NULL) {3476THROW_(vmSymbols::java_lang_NullPointerException(), JNI_FALSE);3477}3478Handle h_obj(THREAD, JNIHandles::resolve(obj));3479return ObjectSynchronizer::current_thread_holds_lock((JavaThread*)THREAD, h_obj);3480JVM_END348134823483JVM_ENTRY(void, JVM_DumpAllStacks(JNIEnv* env, jclass))3484JVMWrapper("JVM_DumpAllStacks");3485VM_PrintThreads op;3486VMThread::execute(&op);3487if (JvmtiExport::should_post_data_dump()) {3488JvmtiExport::post_data_dump();3489}3490JVM_END34913492JVM_ENTRY(void, JVM_SetNativeThreadName(JNIEnv* env, jobject jthread, jstring name))3493JVMWrapper("JVM_SetNativeThreadName");3494ResourceMark rm(THREAD);3495oop java_thread = JNIHandles::resolve_non_null(jthread);3496JavaThread* thr = java_lang_Thread::thread(java_thread);3497// Thread naming only supported for the current thread, doesn't work for3498// target threads.3499if (Thread::current() == thr && !thr->has_attached_via_jni()) {3500// we don't set the name of an attached thread to avoid stepping3501// on other programs3502const char *thread_name = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(name));3503os::set_native_thread_name(thread_name);3504}3505JVM_END35063507// java.lang.SecurityManager ///////////////////////////////////////////////////////////////////////35083509static bool is_trusted_frame(JavaThread* jthread, vframeStream* vfst) {3510assert(jthread->is_Java_thread(), "must be a Java thread");3511if (jthread->privileged_stack_top() == NULL) return false;3512if (jthread->privileged_stack_top()->frame_id() == vfst->frame_id()) {3513oop loader = jthread->privileged_stack_top()->class_loader();3514if (loader == NULL) return true;3515bool trusted = java_lang_ClassLoader::is_trusted_loader(loader);3516if (trusted) return true;3517}3518return false;3519}35203521JVM_ENTRY(jclass, JVM_CurrentLoadedClass(JNIEnv *env))3522JVMWrapper("JVM_CurrentLoadedClass");3523ResourceMark rm(THREAD);35243525for (vframeStream vfst(thread); !vfst.at_end(); vfst.next()) {3526// if a method in a class in a trusted loader is in a doPrivileged, return NULL3527bool trusted = is_trusted_frame(thread, &vfst);3528if (trusted) return NULL;35293530Method* m = vfst.method();3531if (!m->is_native()) {3532InstanceKlass* holder = m->method_holder();3533oop loader = holder->class_loader();3534if (loader != NULL && !java_lang_ClassLoader::is_trusted_loader(loader)) {3535return (jclass) JNIHandles::make_local(env, holder->java_mirror());3536}3537}3538}3539return NULL;3540JVM_END354135423543JVM_ENTRY(jobject, JVM_CurrentClassLoader(JNIEnv *env))3544JVMWrapper("JVM_CurrentClassLoader");3545ResourceMark rm(THREAD);35463547for (vframeStream vfst(thread); !vfst.at_end(); vfst.next()) {35483549// if a method in a class in a trusted loader is in a doPrivileged, return NULL3550bool trusted = is_trusted_frame(thread, &vfst);3551if (trusted) return NULL;35523553Method* m = vfst.method();3554if (!m->is_native()) {3555InstanceKlass* holder = m->method_holder();3556assert(holder->is_klass(), "just checking");3557oop loader = holder->class_loader();3558if (loader != NULL && !java_lang_ClassLoader::is_trusted_loader(loader)) {3559return JNIHandles::make_local(env, loader);3560}3561}3562}3563return NULL;3564JVM_END356535663567JVM_ENTRY(jobjectArray, JVM_GetClassContext(JNIEnv *env))3568JVMWrapper("JVM_GetClassContext");3569ResourceMark rm(THREAD);3570JvmtiVMObjectAllocEventCollector oam;3571vframeStream vfst(thread);35723573if (SystemDictionary::reflect_CallerSensitive_klass() != NULL) {3574// This must only be called from SecurityManager.getClassContext3575Method* m = vfst.method();3576if (!(m->method_holder() == SystemDictionary::SecurityManager_klass() &&3577m->name() == vmSymbols::getClassContext_name() &&3578m->signature() == vmSymbols::void_class_array_signature())) {3579THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), "JVM_GetClassContext must only be called from SecurityManager.getClassContext");3580}3581}35823583// Collect method holders3584GrowableArray<KlassHandle>* klass_array = new GrowableArray<KlassHandle>();3585for (; !vfst.at_end(); vfst.security_next()) {3586Method* m = vfst.method();3587// Native frames are not returned3588if (!m->is_ignored_by_security_stack_walk() && !m->is_native()) {3589Klass* holder = m->method_holder();3590assert(holder->is_klass(), "just checking");3591klass_array->append(holder);3592}3593}35943595// Create result array of type [Ljava/lang/Class;3596objArrayOop result = oopFactory::new_objArray(SystemDictionary::Class_klass(), klass_array->length(), CHECK_NULL);3597// Fill in mirrors corresponding to method holders3598for (int i = 0; i < klass_array->length(); i++) {3599result->obj_at_put(i, klass_array->at(i)->java_mirror());3600}36013602return (jobjectArray) JNIHandles::make_local(env, result);3603JVM_END360436053606JVM_ENTRY(jint, JVM_ClassDepth(JNIEnv *env, jstring name))3607JVMWrapper("JVM_ClassDepth");3608ResourceMark rm(THREAD);3609Handle h_name (THREAD, JNIHandles::resolve_non_null(name));3610Handle class_name_str = java_lang_String::internalize_classname(h_name, CHECK_0);36113612const char* str = java_lang_String::as_utf8_string(class_name_str());3613TempNewSymbol class_name_sym = SymbolTable::probe(str, (int)strlen(str));3614if (class_name_sym == NULL) {3615return -1;3616}36173618int depth = 0;36193620for(vframeStream vfst(thread); !vfst.at_end(); vfst.next()) {3621if (!vfst.method()->is_native()) {3622InstanceKlass* holder = vfst.method()->method_holder();3623assert(holder->is_klass(), "just checking");3624if (holder->name() == class_name_sym) {3625return depth;3626}3627depth++;3628}3629}3630return -1;3631JVM_END363236333634JVM_ENTRY(jint, JVM_ClassLoaderDepth(JNIEnv *env))3635JVMWrapper("JVM_ClassLoaderDepth");3636ResourceMark rm(THREAD);3637int depth = 0;3638for (vframeStream vfst(thread); !vfst.at_end(); vfst.next()) {3639// if a method in a class in a trusted loader is in a doPrivileged, return -13640bool trusted = is_trusted_frame(thread, &vfst);3641if (trusted) return -1;36423643Method* m = vfst.method();3644if (!m->is_native()) {3645InstanceKlass* holder = m->method_holder();3646assert(holder->is_klass(), "just checking");3647oop loader = holder->class_loader();3648if (loader != NULL && !java_lang_ClassLoader::is_trusted_loader(loader)) {3649return depth;3650}3651depth++;3652}3653}3654return -1;3655JVM_END365636573658// java.lang.Package ////////////////////////////////////////////////////////////////365936603661JVM_ENTRY(jstring, JVM_GetSystemPackage(JNIEnv *env, jstring name))3662JVMWrapper("JVM_GetSystemPackage");3663ResourceMark rm(THREAD);3664JvmtiVMObjectAllocEventCollector oam;3665char* str = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(name));3666oop result = ClassLoader::get_system_package(str, CHECK_NULL);3667return (jstring) JNIHandles::make_local(result);3668JVM_END366936703671JVM_ENTRY(jobjectArray, JVM_GetSystemPackages(JNIEnv *env))3672JVMWrapper("JVM_GetSystemPackages");3673JvmtiVMObjectAllocEventCollector oam;3674objArrayOop result = ClassLoader::get_system_packages(CHECK_NULL);3675return (jobjectArray) JNIHandles::make_local(result);3676JVM_END367736783679// ObjectInputStream ///////////////////////////////////////////////////////////////36803681bool force_verify_field_access(Klass* current_class, Klass* field_class, AccessFlags access, bool classloader_only) {3682if (current_class == NULL) {3683return true;3684}3685if ((current_class == field_class) || access.is_public()) {3686return true;3687}36883689if (access.is_protected()) {3690// See if current_class is a subclass of field_class3691if (current_class->is_subclass_of(field_class)) {3692return true;3693}3694}36953696return (!access.is_private() && InstanceKlass::cast(current_class)->is_same_class_package(field_class));3697}369836993700// JVM_AllocateNewObject and JVM_AllocateNewArray are unused as of 1.43701JVM_ENTRY(jobject, JVM_AllocateNewObject(JNIEnv *env, jobject receiver, jclass currClass, jclass initClass))3702JVMWrapper("JVM_AllocateNewObject");3703JvmtiVMObjectAllocEventCollector oam;3704// Receiver is not used3705oop curr_mirror = JNIHandles::resolve_non_null(currClass);3706oop init_mirror = JNIHandles::resolve_non_null(initClass);37073708// Cannot instantiate primitive types3709if (java_lang_Class::is_primitive(curr_mirror) || java_lang_Class::is_primitive(init_mirror)) {3710ResourceMark rm(THREAD);3711THROW_0(vmSymbols::java_lang_InvalidClassException());3712}37133714// Arrays not allowed here, must use JVM_AllocateNewArray3715if (java_lang_Class::as_Klass(curr_mirror)->oop_is_array() ||3716java_lang_Class::as_Klass(init_mirror)->oop_is_array()) {3717ResourceMark rm(THREAD);3718THROW_0(vmSymbols::java_lang_InvalidClassException());3719}37203721instanceKlassHandle curr_klass (THREAD, java_lang_Class::as_Klass(curr_mirror));3722instanceKlassHandle init_klass (THREAD, java_lang_Class::as_Klass(init_mirror));37233724assert(curr_klass->is_subclass_of(init_klass()), "just checking");37253726// Interfaces, abstract classes, and java.lang.Class classes cannot be instantiated directly.3727curr_klass->check_valid_for_instantiation(false, CHECK_NULL);37283729// Make sure klass is initialized, since we are about to instantiate one of them.3730curr_klass->initialize(CHECK_NULL);37313732methodHandle m (THREAD,3733init_klass->find_method(vmSymbols::object_initializer_name(),3734vmSymbols::void_method_signature()));3735if (m.is_null()) {3736ResourceMark rm(THREAD);3737THROW_MSG_0(vmSymbols::java_lang_NoSuchMethodError(),3738Method::name_and_sig_as_C_string(init_klass(),3739vmSymbols::object_initializer_name(),3740vmSymbols::void_method_signature()));3741}37423743if (curr_klass == init_klass && !m->is_public()) {3744// Calling the constructor for class 'curr_klass'.3745// Only allow calls to a public no-arg constructor.3746// This path corresponds to creating an Externalizable object.3747THROW_0(vmSymbols::java_lang_IllegalAccessException());3748}37493750if (!force_verify_field_access(curr_klass(), init_klass(), m->access_flags(), false)) {3751// subclass 'curr_klass' does not have access to no-arg constructor of 'initcb'3752THROW_0(vmSymbols::java_lang_IllegalAccessException());3753}37543755Handle obj = curr_klass->allocate_instance_handle(CHECK_NULL);3756// Call constructor m. This might call a constructor higher up in the hierachy3757JavaCalls::call_default_constructor(thread, m, obj, CHECK_NULL);37583759return JNIHandles::make_local(obj());3760JVM_END376137623763JVM_ENTRY(jobject, JVM_AllocateNewArray(JNIEnv *env, jobject obj, jclass currClass, jint length))3764JVMWrapper("JVM_AllocateNewArray");3765JvmtiVMObjectAllocEventCollector oam;3766oop mirror = JNIHandles::resolve_non_null(currClass);37673768if (java_lang_Class::is_primitive(mirror)) {3769THROW_0(vmSymbols::java_lang_InvalidClassException());3770}3771Klass* k = java_lang_Class::as_Klass(mirror);3772oop result;37733774if (k->oop_is_typeArray()) {3775// typeArray3776result = TypeArrayKlass::cast(k)->allocate(length, CHECK_NULL);3777} else if (k->oop_is_objArray()) {3778// objArray3779ObjArrayKlass* oak = ObjArrayKlass::cast(k);3780oak->initialize(CHECK_NULL); // make sure class is initialized (matches Classic VM behavior)3781result = oak->allocate(length, CHECK_NULL);3782} else {3783THROW_0(vmSymbols::java_lang_InvalidClassException());3784}3785return JNIHandles::make_local(env, result);3786JVM_END378737883789// Returns first non-privileged class loader on the stack (excluding reflection3790// generated frames) or null if only classes loaded by the boot class loader3791// and extension class loader are found on the stack.37923793JVM_ENTRY(jobject, JVM_LatestUserDefinedLoader(JNIEnv *env))3794for (vframeStream vfst(thread); !vfst.at_end(); vfst.next()) {3795// UseNewReflection3796vfst.skip_reflection_related_frames(); // Only needed for 1.4 reflection3797oop loader = vfst.method()->method_holder()->class_loader();3798if (loader != NULL && !SystemDictionary::is_ext_class_loader(loader)) {3799return JNIHandles::make_local(env, loader);3800}3801}3802return NULL;3803JVM_END380438053806// Load a class relative to the most recent class on the stack with a non-null3807// classloader.3808// This function has been deprecated and should not be considered part of the3809// specified JVM interface.38103811JVM_ENTRY(jclass, JVM_LoadClass0(JNIEnv *env, jobject receiver,3812jclass currClass, jstring currClassName))3813JVMWrapper("JVM_LoadClass0");3814// Receiver is not used3815ResourceMark rm(THREAD);38163817// Class name argument is not guaranteed to be in internal format3818Handle classname (THREAD, JNIHandles::resolve_non_null(currClassName));3819Handle string = java_lang_String::internalize_classname(classname, CHECK_NULL);38203821const char* str = java_lang_String::as_utf8_string(string());38223823if (str == NULL || (int)strlen(str) > Symbol::max_length()) {3824// It's impossible to create this class; the name cannot fit3825// into the constant pool.3826THROW_MSG_0(vmSymbols::java_lang_NoClassDefFoundError(), str);3827}38283829TempNewSymbol name = SymbolTable::new_symbol(str, CHECK_NULL);3830Handle curr_klass (THREAD, JNIHandles::resolve(currClass));3831// Find the most recent class on the stack with a non-null classloader3832oop loader = NULL;3833oop protection_domain = NULL;3834if (curr_klass.is_null()) {3835for (vframeStream vfst(thread);3836!vfst.at_end() && loader == NULL;3837vfst.next()) {3838if (!vfst.method()->is_native()) {3839InstanceKlass* holder = vfst.method()->method_holder();3840loader = holder->class_loader();3841protection_domain = holder->protection_domain();3842}3843}3844} else {3845Klass* curr_klass_oop = java_lang_Class::as_Klass(curr_klass());3846loader = InstanceKlass::cast(curr_klass_oop)->class_loader();3847protection_domain = InstanceKlass::cast(curr_klass_oop)->protection_domain();3848}3849Handle h_loader(THREAD, loader);3850Handle h_prot (THREAD, protection_domain);3851jclass result = find_class_from_class_loader(env, name, true, h_loader, h_prot,3852false, thread);3853if (TraceClassResolution && result != NULL) {3854trace_class_resolution(java_lang_Class::as_Klass(JNIHandles::resolve_non_null(result)));3855}3856return result;3857JVM_END385838593860// Array ///////////////////////////////////////////////////////////////////////////////////////////386138623863// resolve array handle and check arguments3864static inline arrayOop check_array(JNIEnv *env, jobject arr, bool type_array_only, TRAPS) {3865if (arr == NULL) {3866THROW_0(vmSymbols::java_lang_NullPointerException());3867}3868oop a = JNIHandles::resolve_non_null(arr);3869if (!a->is_array() || (type_array_only && !a->is_typeArray())) {3870THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Argument is not an array");3871}3872return arrayOop(a);3873}387438753876JVM_ENTRY(jint, JVM_GetArrayLength(JNIEnv *env, jobject arr))3877JVMWrapper("JVM_GetArrayLength");3878arrayOop a = check_array(env, arr, false, CHECK_0);3879return a->length();3880JVM_END388138823883JVM_ENTRY(jobject, JVM_GetArrayElement(JNIEnv *env, jobject arr, jint index))3884JVMWrapper("JVM_Array_Get");3885JvmtiVMObjectAllocEventCollector oam;3886arrayOop a = check_array(env, arr, false, CHECK_NULL);3887jvalue value;3888BasicType type = Reflection::array_get(&value, a, index, CHECK_NULL);3889oop box = Reflection::box(&value, type, CHECK_NULL);3890return JNIHandles::make_local(env, box);3891JVM_END389238933894JVM_ENTRY(jvalue, JVM_GetPrimitiveArrayElement(JNIEnv *env, jobject arr, jint index, jint wCode))3895JVMWrapper("JVM_GetPrimitiveArrayElement");3896jvalue value;3897value.i = 0; // to initialize value before getting used in CHECK3898arrayOop a = check_array(env, arr, true, CHECK_(value));3899assert(a->is_typeArray(), "just checking");3900BasicType type = Reflection::array_get(&value, a, index, CHECK_(value));3901BasicType wide_type = (BasicType) wCode;3902if (type != wide_type) {3903Reflection::widen(&value, type, wide_type, CHECK_(value));3904}3905return value;3906JVM_END390739083909JVM_ENTRY(void, JVM_SetArrayElement(JNIEnv *env, jobject arr, jint index, jobject val))3910JVMWrapper("JVM_SetArrayElement");3911arrayOop a = check_array(env, arr, false, CHECK);3912oop box = JNIHandles::resolve(val);3913jvalue value;3914value.i = 0; // to initialize value before getting used in CHECK3915BasicType value_type;3916if (a->is_objArray()) {3917// Make sure we do no unbox e.g. java/lang/Integer instances when storing into an object array3918value_type = Reflection::unbox_for_regular_object(box, &value);3919} else {3920value_type = Reflection::unbox_for_primitive(box, &value, CHECK);3921}3922Reflection::array_set(&value, a, index, value_type, CHECK);3923JVM_END392439253926JVM_ENTRY(void, JVM_SetPrimitiveArrayElement(JNIEnv *env, jobject arr, jint index, jvalue v, unsigned char vCode))3927JVMWrapper("JVM_SetPrimitiveArrayElement");3928arrayOop a = check_array(env, arr, true, CHECK);3929assert(a->is_typeArray(), "just checking");3930BasicType value_type = (BasicType) vCode;3931Reflection::array_set(&v, a, index, value_type, CHECK);3932JVM_END393339343935JVM_ENTRY(jobject, JVM_NewArray(JNIEnv *env, jclass eltClass, jint length))3936JVMWrapper("JVM_NewArray");3937JvmtiVMObjectAllocEventCollector oam;3938oop element_mirror = JNIHandles::resolve(eltClass);3939oop result = Reflection::reflect_new_array(element_mirror, length, CHECK_NULL);3940return JNIHandles::make_local(env, result);3941JVM_END394239433944JVM_ENTRY(jobject, JVM_NewMultiArray(JNIEnv *env, jclass eltClass, jintArray dim))3945JVMWrapper("JVM_NewMultiArray");3946JvmtiVMObjectAllocEventCollector oam;3947arrayOop dim_array = check_array(env, dim, true, CHECK_NULL);3948oop element_mirror = JNIHandles::resolve(eltClass);3949assert(dim_array->is_typeArray(), "just checking");3950oop result = Reflection::reflect_new_multi_array(element_mirror, typeArrayOop(dim_array), CHECK_NULL);3951return JNIHandles::make_local(env, result);3952JVM_END395339543955// Networking library support ////////////////////////////////////////////////////////////////////39563957JVM_LEAF(jint, JVM_InitializeSocketLibrary())3958JVMWrapper("JVM_InitializeSocketLibrary");3959return 0;3960JVM_END396139623963JVM_LEAF(jint, JVM_Socket(jint domain, jint type, jint protocol))3964JVMWrapper("JVM_Socket");3965return os::socket(domain, type, protocol);3966JVM_END396739683969JVM_LEAF(jint, JVM_SocketClose(jint fd))3970JVMWrapper2("JVM_SocketClose (0x%x)", fd);3971//%note jvm_r63972return os::socket_close(fd);3973JVM_END397439753976JVM_LEAF(jint, JVM_SocketShutdown(jint fd, jint howto))3977JVMWrapper2("JVM_SocketShutdown (0x%x)", fd);3978//%note jvm_r63979return os::socket_shutdown(fd, howto);3980JVM_END398139823983JVM_LEAF(jint, JVM_Recv(jint fd, char *buf, jint nBytes, jint flags))3984JVMWrapper2("JVM_Recv (0x%x)", fd);3985//%note jvm_r63986return os::recv(fd, buf, (size_t)nBytes, (uint)flags);3987JVM_END398839893990JVM_LEAF(jint, JVM_Send(jint fd, char *buf, jint nBytes, jint flags))3991JVMWrapper2("JVM_Send (0x%x)", fd);3992//%note jvm_r63993return os::send(fd, buf, (size_t)nBytes, (uint)flags);3994JVM_END399539963997JVM_LEAF(jint, JVM_Timeout(int fd, long timeout))3998JVMWrapper2("JVM_Timeout (0x%x)", fd);3999//%note jvm_r64000return os::timeout(fd, timeout);4001JVM_END400240034004JVM_LEAF(jint, JVM_Listen(jint fd, jint count))4005JVMWrapper2("JVM_Listen (0x%x)", fd);4006//%note jvm_r64007return os::listen(fd, count);4008JVM_END400940104011JVM_LEAF(jint, JVM_Connect(jint fd, struct sockaddr *him, jint len))4012JVMWrapper2("JVM_Connect (0x%x)", fd);4013//%note jvm_r64014return os::connect(fd, him, (socklen_t)len);4015JVM_END401640174018JVM_LEAF(jint, JVM_Bind(jint fd, struct sockaddr *him, jint len))4019JVMWrapper2("JVM_Bind (0x%x)", fd);4020//%note jvm_r64021return os::bind(fd, him, (socklen_t)len);4022JVM_END402340244025JVM_LEAF(jint, JVM_Accept(jint fd, struct sockaddr *him, jint *len))4026JVMWrapper2("JVM_Accept (0x%x)", fd);4027//%note jvm_r64028socklen_t socklen = (socklen_t)(*len);4029jint result = os::accept(fd, him, &socklen);4030*len = (jint)socklen;4031return result;4032JVM_END403340344035JVM_LEAF(jint, JVM_RecvFrom(jint fd, char *buf, int nBytes, int flags, struct sockaddr *from, int *fromlen))4036JVMWrapper2("JVM_RecvFrom (0x%x)", fd);4037//%note jvm_r64038socklen_t socklen = (socklen_t)(*fromlen);4039jint result = os::recvfrom(fd, buf, (size_t)nBytes, (uint)flags, from, &socklen);4040*fromlen = (int)socklen;4041return result;4042JVM_END404340444045JVM_LEAF(jint, JVM_GetSockName(jint fd, struct sockaddr *him, int *len))4046JVMWrapper2("JVM_GetSockName (0x%x)", fd);4047//%note jvm_r64048socklen_t socklen = (socklen_t)(*len);4049jint result = os::get_sock_name(fd, him, &socklen);4050*len = (int)socklen;4051return result;4052JVM_END405340544055JVM_LEAF(jint, JVM_SendTo(jint fd, char *buf, int len, int flags, struct sockaddr *to, int tolen))4056JVMWrapper2("JVM_SendTo (0x%x)", fd);4057//%note jvm_r64058return os::sendto(fd, buf, (size_t)len, (uint)flags, to, (socklen_t)tolen);4059JVM_END406040614062JVM_LEAF(jint, JVM_SocketAvailable(jint fd, jint *pbytes))4063JVMWrapper2("JVM_SocketAvailable (0x%x)", fd);4064//%note jvm_r64065return os::socket_available(fd, pbytes);4066JVM_END406740684069JVM_LEAF(jint, JVM_GetSockOpt(jint fd, int level, int optname, char *optval, int *optlen))4070JVMWrapper2("JVM_GetSockOpt (0x%x)", fd);4071//%note jvm_r64072socklen_t socklen = (socklen_t)(*optlen);4073jint result = os::get_sock_opt(fd, level, optname, optval, &socklen);4074*optlen = (int)socklen;4075return result;4076JVM_END407740784079JVM_LEAF(jint, JVM_SetSockOpt(jint fd, int level, int optname, const char *optval, int optlen))4080JVMWrapper2("JVM_GetSockOpt (0x%x)", fd);4081//%note jvm_r64082return os::set_sock_opt(fd, level, optname, optval, (socklen_t)optlen);4083JVM_END408440854086JVM_LEAF(int, JVM_GetHostName(char* name, int namelen))4087JVMWrapper("JVM_GetHostName");4088return os::get_host_name(name, namelen);4089JVM_END409040914092// Library support ///////////////////////////////////////////////////////////////////////////40934094JVM_ENTRY_NO_ENV(void*, JVM_LoadLibrary(const char* name))4095//%note jvm_ct4096JVMWrapper2("JVM_LoadLibrary (%s)", name);4097char ebuf[1024];4098void *load_result;4099{4100ThreadToNativeFromVM ttnfvm(thread);4101load_result = os::dll_load(name, ebuf, sizeof ebuf);4102}4103if (load_result == NULL) {4104char msg[1024];4105jio_snprintf(msg, sizeof msg, "%s: %s", name, ebuf);4106// Since 'ebuf' may contain a string encoded using4107// platform encoding scheme, we need to pass4108// Exceptions::unsafe_to_utf8 to the new_exception method4109// as the last argument. See bug 6367357.4110Handle h_exception =4111Exceptions::new_exception(thread,4112vmSymbols::java_lang_UnsatisfiedLinkError(),4113msg, Exceptions::unsafe_to_utf8);41144115THROW_HANDLE_0(h_exception);4116}4117return load_result;4118JVM_END411941204121JVM_LEAF(void, JVM_UnloadLibrary(void* handle))4122JVMWrapper("JVM_UnloadLibrary");4123os::dll_unload(handle);4124JVM_END412541264127JVM_LEAF(void*, JVM_FindLibraryEntry(void* handle, const char* name))4128JVMWrapper2("JVM_FindLibraryEntry (%s)", name);4129return os::dll_lookup(handle, name);4130JVM_END413141324133// Floating point support ////////////////////////////////////////////////////////////////////41344135JVM_LEAF(jboolean, JVM_IsNaN(jdouble a))4136JVMWrapper("JVM_IsNaN");4137return g_isnan(a);4138JVM_END413941404141// JNI version ///////////////////////////////////////////////////////////////////////////////41424143JVM_LEAF(jboolean, JVM_IsSupportedJNIVersion(jint version))4144JVMWrapper2("JVM_IsSupportedJNIVersion (%d)", version);4145return Threads::is_supported_jni_version_including_1_1(version);4146JVM_END414741484149// String support ///////////////////////////////////////////////////////////////////////////41504151JVM_ENTRY(jstring, JVM_InternString(JNIEnv *env, jstring str))4152JVMWrapper("JVM_InternString");4153JvmtiVMObjectAllocEventCollector oam;4154if (str == NULL) return NULL;4155oop string = JNIHandles::resolve_non_null(str);4156oop result = StringTable::intern(string, CHECK_NULL);4157return (jstring) JNIHandles::make_local(env, result);4158JVM_END415941604161// Raw monitor support //////////////////////////////////////////////////////////////////////41624163// The lock routine below calls lock_without_safepoint_check in order to get a raw lock4164// without interfering with the safepoint mechanism. The routines are not JVM_LEAF because4165// they might be called by non-java threads. The JVM_LEAF installs a NoHandleMark check4166// that only works with java threads.416741684169JNIEXPORT void* JNICALL JVM_RawMonitorCreate(void) {4170VM_Exit::block_if_vm_exited();4171JVMWrapper("JVM_RawMonitorCreate");4172return new Mutex(Mutex::native, "JVM_RawMonitorCreate");4173}417441754176JNIEXPORT void JNICALL JVM_RawMonitorDestroy(void *mon) {4177VM_Exit::block_if_vm_exited();4178JVMWrapper("JVM_RawMonitorDestroy");4179delete ((Mutex*) mon);4180}418141824183JNIEXPORT jint JNICALL JVM_RawMonitorEnter(void *mon) {4184VM_Exit::block_if_vm_exited();4185JVMWrapper("JVM_RawMonitorEnter");4186((Mutex*) mon)->jvm_raw_lock();4187return 0;4188}418941904191JNIEXPORT void JNICALL JVM_RawMonitorExit(void *mon) {4192VM_Exit::block_if_vm_exited();4193JVMWrapper("JVM_RawMonitorExit");4194((Mutex*) mon)->jvm_raw_unlock();4195}419641974198// Support for Serialization41994200typedef jfloat (JNICALL *IntBitsToFloatFn )(JNIEnv* env, jclass cb, jint value);4201typedef jdouble (JNICALL *LongBitsToDoubleFn)(JNIEnv* env, jclass cb, jlong value);4202typedef jint (JNICALL *FloatToIntBitsFn )(JNIEnv* env, jclass cb, jfloat value);4203typedef jlong (JNICALL *DoubleToLongBitsFn)(JNIEnv* env, jclass cb, jdouble value);42044205static IntBitsToFloatFn int_bits_to_float_fn = NULL;4206static LongBitsToDoubleFn long_bits_to_double_fn = NULL;4207static FloatToIntBitsFn float_to_int_bits_fn = NULL;4208static DoubleToLongBitsFn double_to_long_bits_fn = NULL;420942104211void initialize_converter_functions() {4212if (JDK_Version::is_gte_jdk14x_version()) {4213// These functions only exist for compatibility with 1.3.1 and earlier4214return;4215}42164217// called from universe_post_init()4218assert(4219int_bits_to_float_fn == NULL &&4220long_bits_to_double_fn == NULL &&4221float_to_int_bits_fn == NULL &&4222double_to_long_bits_fn == NULL ,4223"initialization done twice"4224);4225// initialize4226int_bits_to_float_fn = CAST_TO_FN_PTR(IntBitsToFloatFn , NativeLookup::base_library_lookup("java/lang/Float" , "intBitsToFloat" , "(I)F"));4227long_bits_to_double_fn = CAST_TO_FN_PTR(LongBitsToDoubleFn, NativeLookup::base_library_lookup("java/lang/Double", "longBitsToDouble", "(J)D"));4228float_to_int_bits_fn = CAST_TO_FN_PTR(FloatToIntBitsFn , NativeLookup::base_library_lookup("java/lang/Float" , "floatToIntBits" , "(F)I"));4229double_to_long_bits_fn = CAST_TO_FN_PTR(DoubleToLongBitsFn, NativeLookup::base_library_lookup("java/lang/Double", "doubleToLongBits", "(D)J"));4230// verify4231assert(4232int_bits_to_float_fn != NULL &&4233long_bits_to_double_fn != NULL &&4234float_to_int_bits_fn != NULL &&4235double_to_long_bits_fn != NULL ,4236"initialization failed"4237);4238}4239424042414242// Shared JNI/JVM entry points //////////////////////////////////////////////////////////////42434244jclass find_class_from_class_loader(JNIEnv* env, Symbol* name, jboolean init,4245Handle loader, Handle protection_domain,4246jboolean throwError, TRAPS) {4247// Security Note:4248// The Java level wrapper will perform the necessary security check allowing4249// us to pass the NULL as the initiating class loader. The VM is responsible for4250// the checkPackageAccess relative to the initiating class loader via the4251// protection_domain. The protection_domain is passed as NULL by the java code4252// if there is no security manager in 3-arg Class.forName().4253Klass* klass = SystemDictionary::resolve_or_fail(name, loader, protection_domain, throwError != 0, CHECK_NULL);42544255KlassHandle klass_handle(THREAD, klass);4256// Check if we should initialize the class4257if (init && klass_handle->oop_is_instance()) {4258klass_handle->initialize(CHECK_NULL);4259}4260return (jclass) JNIHandles::make_local(env, klass_handle->java_mirror());4261}426242634264// Internal SQE debugging support ///////////////////////////////////////////////////////////42654266#ifndef PRODUCT42674268extern "C" {4269JNIEXPORT jboolean JNICALL JVM_AccessVMBooleanFlag(const char* name, jboolean* value, jboolean is_get);4270JNIEXPORT jboolean JNICALL JVM_AccessVMIntFlag(const char* name, jint* value, jboolean is_get);4271JNIEXPORT void JNICALL JVM_VMBreakPoint(JNIEnv *env, jobject obj);4272}42734274JVM_LEAF(jboolean, JVM_AccessVMBooleanFlag(const char* name, jboolean* value, jboolean is_get))4275JVMWrapper("JVM_AccessBoolVMFlag");4276return is_get ? CommandLineFlags::boolAt((char*) name, (bool*) value) : CommandLineFlags::boolAtPut((char*) name, (bool*) value, Flag::INTERNAL);4277JVM_END42784279JVM_LEAF(jboolean, JVM_AccessVMIntFlag(const char* name, jint* value, jboolean is_get))4280JVMWrapper("JVM_AccessVMIntFlag");4281intx v;4282jboolean result = is_get ? CommandLineFlags::intxAt((char*) name, &v) : CommandLineFlags::intxAtPut((char*) name, &v, Flag::INTERNAL);4283*value = (jint)v;4284return result;4285JVM_END428642874288JVM_ENTRY(void, JVM_VMBreakPoint(JNIEnv *env, jobject obj))4289JVMWrapper("JVM_VMBreakPoint");4290oop the_obj = JNIHandles::resolve(obj);4291BREAKPOINT;4292JVM_END429342944295#endif429642974298// Method ///////////////////////////////////////////////////////////////////////////////////////////42994300JVM_ENTRY(jobject, JVM_InvokeMethod(JNIEnv *env, jobject method, jobject obj, jobjectArray args0))4301JVMWrapper("JVM_InvokeMethod");4302Handle method_handle;4303if (thread->stack_available((address) &method_handle) >= JVMInvokeMethodSlack) {4304method_handle = Handle(THREAD, JNIHandles::resolve(method));4305Handle receiver(THREAD, JNIHandles::resolve(obj));4306objArrayHandle args(THREAD, objArrayOop(JNIHandles::resolve(args0)));4307oop result = Reflection::invoke_method(method_handle(), receiver, args, CHECK_NULL);4308jobject res = JNIHandles::make_local(env, result);4309if (JvmtiExport::should_post_vm_object_alloc()) {4310oop ret_type = java_lang_reflect_Method::return_type(method_handle());4311assert(ret_type != NULL, "sanity check: ret_type oop must not be NULL!");4312if (java_lang_Class::is_primitive(ret_type)) {4313// Only for primitive type vm allocates memory for java object.4314// See box() method.4315JvmtiExport::post_vm_object_alloc(JavaThread::current(), result);4316}4317}4318return res;4319} else {4320THROW_0(vmSymbols::java_lang_StackOverflowError());4321}4322JVM_END432343244325JVM_ENTRY(jobject, JVM_NewInstanceFromConstructor(JNIEnv *env, jobject c, jobjectArray args0))4326JVMWrapper("JVM_NewInstanceFromConstructor");4327oop constructor_mirror = JNIHandles::resolve(c);4328objArrayHandle args(THREAD, objArrayOop(JNIHandles::resolve(args0)));4329oop result = Reflection::invoke_constructor(constructor_mirror, args, CHECK_NULL);4330jobject res = JNIHandles::make_local(env, result);4331if (JvmtiExport::should_post_vm_object_alloc()) {4332JvmtiExport::post_vm_object_alloc(JavaThread::current(), result);4333}4334return res;4335JVM_END43364337// Atomic ///////////////////////////////////////////////////////////////////////////////////////////43384339JVM_LEAF(jboolean, JVM_SupportsCX8())4340JVMWrapper("JVM_SupportsCX8");4341return VM_Version::supports_cx8();4342JVM_END434343444345JVM_ENTRY(jboolean, JVM_CX8Field(JNIEnv *env, jobject obj, jfieldID fid, jlong oldVal, jlong newVal))4346JVMWrapper("JVM_CX8Field");4347jlong res;4348oop o = JNIHandles::resolve(obj);4349intptr_t fldOffs = jfieldIDWorkaround::from_instance_jfieldID(o->klass(), fid);4350volatile jlong* addr = (volatile jlong*)((address)o + fldOffs);43514352assert(VM_Version::supports_cx8(), "cx8 not supported");4353res = Atomic::cmpxchg(newVal, addr, oldVal);43544355return res == oldVal;4356JVM_END43574358// DTrace ///////////////////////////////////////////////////////////////////43594360JVM_ENTRY(jint, JVM_DTraceGetVersion(JNIEnv* env))4361JVMWrapper("JVM_DTraceGetVersion");4362return (jint)JVM_TRACING_DTRACE_VERSION;4363JVM_END43644365JVM_ENTRY(jlong,JVM_DTraceActivate(4366JNIEnv* env, jint version, jstring module_name, jint providers_count,4367JVM_DTraceProvider* providers))4368JVMWrapper("JVM_DTraceActivate");4369return DTraceJSDT::activate(4370version, module_name, providers_count, providers, THREAD);4371JVM_END43724373JVM_ENTRY(jboolean,JVM_DTraceIsProbeEnabled(JNIEnv* env, jmethodID method))4374JVMWrapper("JVM_DTraceIsProbeEnabled");4375return DTraceJSDT::is_probe_enabled(method);4376JVM_END43774378JVM_ENTRY(void,JVM_DTraceDispose(JNIEnv* env, jlong handle))4379JVMWrapper("JVM_DTraceDispose");4380DTraceJSDT::dispose(handle);4381JVM_END43824383JVM_ENTRY(jboolean,JVM_DTraceIsSupported(JNIEnv* env))4384JVMWrapper("JVM_DTraceIsSupported");4385return DTraceJSDT::is_supported();4386JVM_END43874388// Returns an array of all live Thread objects (VM internal JavaThreads,4389// jvmti agent threads, and JNI attaching threads are skipped)4390// See CR 6404306 regarding JNI attaching threads4391JVM_ENTRY(jobjectArray, JVM_GetAllThreads(JNIEnv *env, jclass dummy))4392ResourceMark rm(THREAD);4393ThreadsListEnumerator tle(THREAD, false, false);4394JvmtiVMObjectAllocEventCollector oam;43954396int num_threads = tle.num_threads();4397objArrayOop r = oopFactory::new_objArray(SystemDictionary::Thread_klass(), num_threads, CHECK_NULL);4398objArrayHandle threads_ah(THREAD, r);43994400for (int i = 0; i < num_threads; i++) {4401Handle h = tle.get_threadObj(i);4402threads_ah->obj_at_put(i, h());4403}44044405return (jobjectArray) JNIHandles::make_local(env, threads_ah());4406JVM_END440744084409// Support for java.lang.Thread.getStackTrace() and getAllStackTraces() methods4410// Return StackTraceElement[][], each element is the stack trace of a thread in4411// the corresponding entry in the given threads array4412JVM_ENTRY(jobjectArray, JVM_DumpThreads(JNIEnv *env, jclass threadClass, jobjectArray threads))4413JVMWrapper("JVM_DumpThreads");4414JvmtiVMObjectAllocEventCollector oam;44154416// Check if threads is null4417if (threads == NULL) {4418THROW_(vmSymbols::java_lang_NullPointerException(), 0);4419}44204421objArrayOop a = objArrayOop(JNIHandles::resolve_non_null(threads));4422objArrayHandle ah(THREAD, a);4423int num_threads = ah->length();4424// check if threads is non-empty array4425if (num_threads == 0) {4426THROW_(vmSymbols::java_lang_IllegalArgumentException(), 0);4427}44284429// check if threads is not an array of objects of Thread class4430Klass* k = ObjArrayKlass::cast(ah->klass())->element_klass();4431if (k != SystemDictionary::Thread_klass()) {4432THROW_(vmSymbols::java_lang_IllegalArgumentException(), 0);4433}44344435ResourceMark rm(THREAD);44364437GrowableArray<instanceHandle>* thread_handle_array = new GrowableArray<instanceHandle>(num_threads);4438for (int i = 0; i < num_threads; i++) {4439oop thread_obj = ah->obj_at(i);4440instanceHandle h(THREAD, (instanceOop) thread_obj);4441thread_handle_array->append(h);4442}44434444Handle stacktraces = ThreadService::dump_stack_traces(thread_handle_array, num_threads, CHECK_NULL);4445return (jobjectArray)JNIHandles::make_local(env, stacktraces());44464447JVM_END44484449// JVM monitoring and management support4450JVM_ENTRY_NO_ENV(void*, JVM_GetManagement(jint version))4451return Management::get_jmm_interface(version);4452JVM_END44534454// com.sun.tools.attach.VirtualMachine agent properties support4455//4456// Initialize the agent properties with the properties maintained in the VM4457JVM_ENTRY(jobject, JVM_InitAgentProperties(JNIEnv *env, jobject properties))4458JVMWrapper("JVM_InitAgentProperties");4459ResourceMark rm;44604461Handle props(THREAD, JNIHandles::resolve_non_null(properties));44624463PUTPROP(props, "sun.java.command", Arguments::java_command());4464PUTPROP(props, "sun.jvm.flags", Arguments::jvm_flags());4465PUTPROP(props, "sun.jvm.args", Arguments::jvm_args());4466return properties;4467JVM_END44684469JVM_ENTRY(jobjectArray, JVM_GetEnclosingMethodInfo(JNIEnv *env, jclass ofClass))4470{4471JVMWrapper("JVM_GetEnclosingMethodInfo");4472JvmtiVMObjectAllocEventCollector oam;44734474if (ofClass == NULL) {4475return NULL;4476}4477Handle mirror(THREAD, JNIHandles::resolve_non_null(ofClass));4478// Special handling for primitive objects4479if (java_lang_Class::is_primitive(mirror())) {4480return NULL;4481}4482Klass* k = java_lang_Class::as_Klass(mirror());4483if (!k->oop_is_instance()) {4484return NULL;4485}4486instanceKlassHandle ik_h(THREAD, k);4487int encl_method_class_idx = ik_h->enclosing_method_class_index();4488if (encl_method_class_idx == 0) {4489return NULL;4490}4491objArrayOop dest_o = oopFactory::new_objArray(SystemDictionary::Object_klass(), 3, CHECK_NULL);4492objArrayHandle dest(THREAD, dest_o);4493Klass* enc_k = ik_h->constants()->klass_at(encl_method_class_idx, CHECK_NULL);4494dest->obj_at_put(0, enc_k->java_mirror());4495int encl_method_method_idx = ik_h->enclosing_method_method_index();4496if (encl_method_method_idx != 0) {4497Symbol* sym = ik_h->constants()->symbol_at(4498extract_low_short_from_int(4499ik_h->constants()->name_and_type_at(encl_method_method_idx)));4500Handle str = java_lang_String::create_from_symbol(sym, CHECK_NULL);4501dest->obj_at_put(1, str());4502sym = ik_h->constants()->symbol_at(4503extract_high_short_from_int(4504ik_h->constants()->name_and_type_at(encl_method_method_idx)));4505str = java_lang_String::create_from_symbol(sym, CHECK_NULL);4506dest->obj_at_put(2, str());4507}4508return (jobjectArray) JNIHandles::make_local(dest());4509}4510JVM_END45114512JVM_ENTRY(jintArray, JVM_GetThreadStateValues(JNIEnv* env,4513jint javaThreadState))4514{4515// If new thread states are added in future JDK and VM versions,4516// this should check if the JDK version is compatible with thread4517// states supported by the VM. Return NULL if not compatible.4518//4519// This function must map the VM java_lang_Thread::ThreadStatus4520// to the Java thread state that the JDK supports.4521//45224523typeArrayHandle values_h;4524switch (javaThreadState) {4525case JAVA_THREAD_STATE_NEW : {4526typeArrayOop r = oopFactory::new_typeArray(T_INT, 1, CHECK_NULL);4527values_h = typeArrayHandle(THREAD, r);4528values_h->int_at_put(0, java_lang_Thread::NEW);4529break;4530}4531case JAVA_THREAD_STATE_RUNNABLE : {4532typeArrayOop r = oopFactory::new_typeArray(T_INT, 1, CHECK_NULL);4533values_h = typeArrayHandle(THREAD, r);4534values_h->int_at_put(0, java_lang_Thread::RUNNABLE);4535break;4536}4537case JAVA_THREAD_STATE_BLOCKED : {4538typeArrayOop r = oopFactory::new_typeArray(T_INT, 1, CHECK_NULL);4539values_h = typeArrayHandle(THREAD, r);4540values_h->int_at_put(0, java_lang_Thread::BLOCKED_ON_MONITOR_ENTER);4541break;4542}4543case JAVA_THREAD_STATE_WAITING : {4544typeArrayOop r = oopFactory::new_typeArray(T_INT, 2, CHECK_NULL);4545values_h = typeArrayHandle(THREAD, r);4546values_h->int_at_put(0, java_lang_Thread::IN_OBJECT_WAIT);4547values_h->int_at_put(1, java_lang_Thread::PARKED);4548break;4549}4550case JAVA_THREAD_STATE_TIMED_WAITING : {4551typeArrayOop r = oopFactory::new_typeArray(T_INT, 3, CHECK_NULL);4552values_h = typeArrayHandle(THREAD, r);4553values_h->int_at_put(0, java_lang_Thread::SLEEPING);4554values_h->int_at_put(1, java_lang_Thread::IN_OBJECT_WAIT_TIMED);4555values_h->int_at_put(2, java_lang_Thread::PARKED_TIMED);4556break;4557}4558case JAVA_THREAD_STATE_TERMINATED : {4559typeArrayOop r = oopFactory::new_typeArray(T_INT, 1, CHECK_NULL);4560values_h = typeArrayHandle(THREAD, r);4561values_h->int_at_put(0, java_lang_Thread::TERMINATED);4562break;4563}4564default:4565// Unknown state - probably incompatible JDK version4566return NULL;4567}45684569return (jintArray) JNIHandles::make_local(env, values_h());4570}4571JVM_END457245734574JVM_ENTRY(jobjectArray, JVM_GetThreadStateNames(JNIEnv* env,4575jint javaThreadState,4576jintArray values))4577{4578// If new thread states are added in future JDK and VM versions,4579// this should check if the JDK version is compatible with thread4580// states supported by the VM. Return NULL if not compatible.4581//4582// This function must map the VM java_lang_Thread::ThreadStatus4583// to the Java thread state that the JDK supports.4584//45854586ResourceMark rm;45874588// Check if threads is null4589if (values == NULL) {4590THROW_(vmSymbols::java_lang_NullPointerException(), 0);4591}45924593typeArrayOop v = typeArrayOop(JNIHandles::resolve_non_null(values));4594typeArrayHandle values_h(THREAD, v);45954596objArrayHandle names_h;4597switch (javaThreadState) {4598case JAVA_THREAD_STATE_NEW : {4599assert(values_h->length() == 1 &&4600values_h->int_at(0) == java_lang_Thread::NEW,4601"Invalid threadStatus value");46024603objArrayOop r = oopFactory::new_objArray(SystemDictionary::String_klass(),46041, /* only 1 substate */4605CHECK_NULL);4606names_h = objArrayHandle(THREAD, r);4607Handle name = java_lang_String::create_from_str("NEW", CHECK_NULL);4608names_h->obj_at_put(0, name());4609break;4610}4611case JAVA_THREAD_STATE_RUNNABLE : {4612assert(values_h->length() == 1 &&4613values_h->int_at(0) == java_lang_Thread::RUNNABLE,4614"Invalid threadStatus value");46154616objArrayOop r = oopFactory::new_objArray(SystemDictionary::String_klass(),46171, /* only 1 substate */4618CHECK_NULL);4619names_h = objArrayHandle(THREAD, r);4620Handle name = java_lang_String::create_from_str("RUNNABLE", CHECK_NULL);4621names_h->obj_at_put(0, name());4622break;4623}4624case JAVA_THREAD_STATE_BLOCKED : {4625assert(values_h->length() == 1 &&4626values_h->int_at(0) == java_lang_Thread::BLOCKED_ON_MONITOR_ENTER,4627"Invalid threadStatus value");46284629objArrayOop r = oopFactory::new_objArray(SystemDictionary::String_klass(),46301, /* only 1 substate */4631CHECK_NULL);4632names_h = objArrayHandle(THREAD, r);4633Handle name = java_lang_String::create_from_str("BLOCKED", CHECK_NULL);4634names_h->obj_at_put(0, name());4635break;4636}4637case JAVA_THREAD_STATE_WAITING : {4638assert(values_h->length() == 2 &&4639values_h->int_at(0) == java_lang_Thread::IN_OBJECT_WAIT &&4640values_h->int_at(1) == java_lang_Thread::PARKED,4641"Invalid threadStatus value");4642objArrayOop r = oopFactory::new_objArray(SystemDictionary::String_klass(),46432, /* number of substates */4644CHECK_NULL);4645names_h = objArrayHandle(THREAD, r);4646Handle name0 = java_lang_String::create_from_str("WAITING.OBJECT_WAIT",4647CHECK_NULL);4648Handle name1 = java_lang_String::create_from_str("WAITING.PARKED",4649CHECK_NULL);4650names_h->obj_at_put(0, name0());4651names_h->obj_at_put(1, name1());4652break;4653}4654case JAVA_THREAD_STATE_TIMED_WAITING : {4655assert(values_h->length() == 3 &&4656values_h->int_at(0) == java_lang_Thread::SLEEPING &&4657values_h->int_at(1) == java_lang_Thread::IN_OBJECT_WAIT_TIMED &&4658values_h->int_at(2) == java_lang_Thread::PARKED_TIMED,4659"Invalid threadStatus value");4660objArrayOop r = oopFactory::new_objArray(SystemDictionary::String_klass(),46613, /* number of substates */4662CHECK_NULL);4663names_h = objArrayHandle(THREAD, r);4664Handle name0 = java_lang_String::create_from_str("TIMED_WAITING.SLEEPING",4665CHECK_NULL);4666Handle name1 = java_lang_String::create_from_str("TIMED_WAITING.OBJECT_WAIT",4667CHECK_NULL);4668Handle name2 = java_lang_String::create_from_str("TIMED_WAITING.PARKED",4669CHECK_NULL);4670names_h->obj_at_put(0, name0());4671names_h->obj_at_put(1, name1());4672names_h->obj_at_put(2, name2());4673break;4674}4675case JAVA_THREAD_STATE_TERMINATED : {4676assert(values_h->length() == 1 &&4677values_h->int_at(0) == java_lang_Thread::TERMINATED,4678"Invalid threadStatus value");4679objArrayOop r = oopFactory::new_objArray(SystemDictionary::String_klass(),46801, /* only 1 substate */4681CHECK_NULL);4682names_h = objArrayHandle(THREAD, r);4683Handle name = java_lang_String::create_from_str("TERMINATED", CHECK_NULL);4684names_h->obj_at_put(0, name());4685break;4686}4687default:4688// Unknown state - probably incompatible JDK version4689return NULL;4690}4691return (jobjectArray) JNIHandles::make_local(env, names_h());4692}4693JVM_END46944695JVM_ENTRY(void, JVM_GetVersionInfo(JNIEnv* env, jvm_version_info* info, size_t info_size))4696{4697memset(info, 0, info_size);46984699info->jvm_version = Abstract_VM_Version::jvm_version();4700info->update_version = 0; /* 0 in HotSpot Express VM */4701info->special_update_version = 0; /* 0 in HotSpot Express VM */47024703// when we add a new capability in the jvm_version_info struct, we should also4704// consider to expose this new capability in the sun.rt.jvmCapabilities jvmstat4705// counter defined in runtimeService.cpp.4706info->is_attachable = AttachListener::is_attach_supported();4707}4708JVM_END470947104711