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