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