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