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