* Merge from mainline.
[official-gcc.git] / libjava / jni.cc
blobf7d73e5538548ff3cb20260e3c66e279a004df58
1 // jni.cc - JNI implementation, including the jump table.
3 /* Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006
4 Free Software Foundation
6 This file is part of libgcj.
8 This software is copyrighted work licensed under the terms of the
9 Libgcj License. Please consult the file "LIBGCJ_LICENSE" for
10 details. */
12 #include <config.h>
14 #include <stdio.h>
15 #include <stddef.h>
16 #include <string.h>
18 #include <gcj/cni.h>
19 #include <jvm.h>
20 #include <java-assert.h>
21 #include <jni.h>
22 #ifdef ENABLE_JVMPI
23 #include <jvmpi.h>
24 #endif
25 #include <jvmti.h>
27 #include <java/lang/Class.h>
28 #include <java/lang/ClassLoader.h>
29 #include <java/lang/Throwable.h>
30 #include <java/lang/ArrayIndexOutOfBoundsException.h>
31 #include <java/lang/StringIndexOutOfBoundsException.h>
32 #include <java/lang/StringBuffer.h>
33 #include <java/lang/UnsatisfiedLinkError.h>
34 #include <java/lang/InstantiationException.h>
35 #include <java/lang/NoSuchFieldError.h>
36 #include <java/lang/NoSuchMethodError.h>
37 #include <java/lang/reflect/Constructor.h>
38 #include <java/lang/reflect/Method.h>
39 #include <java/lang/reflect/Modifier.h>
40 #include <java/lang/OutOfMemoryError.h>
41 #include <java/lang/Integer.h>
42 #include <java/lang/ThreadGroup.h>
43 #include <java/lang/Thread.h>
44 #include <java/lang/IllegalAccessError.h>
45 #include <java/nio/Buffer.h>
46 #include <java/nio/DirectByteBufferImpl.h>
47 #include <java/nio/DirectByteBufferImpl$ReadWrite.h>
48 #include <java/util/IdentityHashMap.h>
49 #include <gnu/gcj/RawData.h>
50 #include <java/lang/ClassNotFoundException.h>
52 #include <gcj/method.h>
53 #include <gcj/field.h>
55 #include <java-interp.h>
56 #include <java-threads.h>
58 using namespace gcj;
60 // This enum is used to select different template instantiations in
61 // the invocation code.
62 enum invocation_type
64 normal,
65 nonvirtual,
66 static_type,
67 constructor
70 // Forward declarations.
71 extern struct JNINativeInterface _Jv_JNIFunctions;
72 extern struct JNIInvokeInterface _Jv_JNI_InvokeFunctions;
74 // Number of slots in the default frame. The VM must allow at least
75 // 16.
76 #define FRAME_SIZE 16
78 // Mark value indicating this is an overflow frame.
79 #define MARK_NONE 0
80 // Mark value indicating this is a user frame.
81 #define MARK_USER 1
82 // Mark value indicating this is a system frame.
83 #define MARK_SYSTEM 2
85 // This structure is used to keep track of local references.
86 struct _Jv_JNI_LocalFrame
88 // This is true if this frame object represents a pushed frame (eg
89 // from PushLocalFrame).
90 int marker;
92 // Flag to indicate some locals were allocated.
93 int allocated_p;
95 // Number of elements in frame.
96 int size;
98 // Next frame in chain.
99 _Jv_JNI_LocalFrame *next;
101 // The elements. These are allocated using the C "struct hack".
102 jobject vec[0];
105 // This holds a reference count for all local references.
106 static java::util::IdentityHashMap *local_ref_table;
107 // This holds a reference count for all global references.
108 static java::util::IdentityHashMap *global_ref_table;
110 // The only VM.
111 JavaVM *_Jv_the_vm;
113 #ifdef ENABLE_JVMPI
114 // The only JVMPI interface description.
115 static JVMPI_Interface _Jv_JVMPI_Interface;
117 static jint
118 jvmpiEnableEvent (jint event_type, void *)
120 switch (event_type)
122 case JVMPI_EVENT_OBJECT_ALLOC:
123 _Jv_JVMPI_Notify_OBJECT_ALLOC = _Jv_JVMPI_Interface.NotifyEvent;
124 break;
126 case JVMPI_EVENT_THREAD_START:
127 _Jv_JVMPI_Notify_THREAD_START = _Jv_JVMPI_Interface.NotifyEvent;
128 break;
130 case JVMPI_EVENT_THREAD_END:
131 _Jv_JVMPI_Notify_THREAD_END = _Jv_JVMPI_Interface.NotifyEvent;
132 break;
134 default:
135 return JVMPI_NOT_AVAILABLE;
138 return JVMPI_SUCCESS;
141 static jint
142 jvmpiDisableEvent (jint event_type, void *)
144 switch (event_type)
146 case JVMPI_EVENT_OBJECT_ALLOC:
147 _Jv_JVMPI_Notify_OBJECT_ALLOC = NULL;
148 break;
150 default:
151 return JVMPI_NOT_AVAILABLE;
154 return JVMPI_SUCCESS;
156 #endif
160 void
161 _Jv_JNI_Init (void)
163 local_ref_table = new java::util::IdentityHashMap;
164 global_ref_table = new java::util::IdentityHashMap;
166 #ifdef ENABLE_JVMPI
167 _Jv_JVMPI_Interface.version = 1;
168 _Jv_JVMPI_Interface.EnableEvent = &jvmpiEnableEvent;
169 _Jv_JVMPI_Interface.DisableEvent = &jvmpiDisableEvent;
170 _Jv_JVMPI_Interface.EnableGC = &_Jv_EnableGC;
171 _Jv_JVMPI_Interface.DisableGC = &_Jv_DisableGC;
172 _Jv_JVMPI_Interface.RunGC = &_Jv_RunGC;
173 #endif
176 // Tell the GC that a certain pointer is live.
177 static void
178 mark_for_gc (jobject obj, java::util::IdentityHashMap *ref_table)
180 JvSynchronize sync (ref_table);
182 using namespace java::lang;
183 Integer *refcount = (Integer *) ref_table->get (obj);
184 jint val = (refcount == NULL) ? 0 : refcount->intValue ();
185 // FIXME: what about out of memory error?
186 ref_table->put (obj, new Integer (val + 1));
189 // Unmark a pointer.
190 static void
191 unmark_for_gc (jobject obj, java::util::IdentityHashMap *ref_table)
193 JvSynchronize sync (ref_table);
195 using namespace java::lang;
196 Integer *refcount = (Integer *) ref_table->get (obj);
197 JvAssert (refcount);
198 jint val = refcount->intValue () - 1;
199 JvAssert (val >= 0);
200 if (val == 0)
201 ref_table->remove (obj);
202 else
203 // FIXME: what about out of memory error?
204 ref_table->put (obj, new Integer (val));
207 // "Unwrap" some random non-reference type. This exists to simplify
208 // other template functions.
209 template<typename T>
210 static T
211 unwrap (T val)
213 return val;
216 // Unwrap a weak reference, if required.
217 template<typename T>
218 static T *
219 unwrap (T *obj)
221 using namespace gnu::gcj::runtime;
222 // We can compare the class directly because JNIWeakRef is `final'.
223 // Doing it this way is much faster.
224 if (obj == NULL || obj->getClass () != &JNIWeakRef::class$)
225 return obj;
226 JNIWeakRef *wr = reinterpret_cast<JNIWeakRef *> (obj);
227 return reinterpret_cast<T *> (wr->get ());
230 jobject
231 _Jv_UnwrapJNIweakReference (jobject obj)
233 return unwrap (obj);
238 static jobject JNICALL
239 _Jv_JNI_NewGlobalRef (JNIEnv *, jobject obj)
241 // This seems weird but I think it is correct.
242 obj = unwrap (obj);
243 mark_for_gc (obj, global_ref_table);
244 return obj;
247 static void JNICALL
248 _Jv_JNI_DeleteGlobalRef (JNIEnv *, jobject obj)
250 // This seems weird but I think it is correct.
251 obj = unwrap (obj);
253 // NULL is ok here -- the JNI specification doesn't say so, but this
254 // is a no-op.
255 if (! obj)
256 return;
258 unmark_for_gc (obj, global_ref_table);
261 static void JNICALL
262 _Jv_JNI_DeleteLocalRef (JNIEnv *env, jobject obj)
264 _Jv_JNI_LocalFrame *frame;
266 // This seems weird but I think it is correct.
267 obj = unwrap (obj);
269 // NULL is ok here -- the JNI specification doesn't say so, but this
270 // is a no-op.
271 if (! obj)
272 return;
274 for (frame = env->locals; frame != NULL; frame = frame->next)
276 for (int i = 0; i < frame->size; ++i)
278 if (frame->vec[i] == obj)
280 frame->vec[i] = NULL;
281 unmark_for_gc (obj, local_ref_table);
282 return;
286 // Don't go past a marked frame.
287 JvAssert (frame->marker == MARK_NONE);
290 JvAssert (0);
293 static jint JNICALL
294 _Jv_JNI_EnsureLocalCapacity (JNIEnv *env, jint size)
296 // It is easier to just always allocate a new frame of the requested
297 // size. This isn't the most efficient thing, but for now we don't
298 // care. Note that _Jv_JNI_PushLocalFrame relies on this right now.
300 _Jv_JNI_LocalFrame *frame;
303 frame = (_Jv_JNI_LocalFrame *) _Jv_Malloc (sizeof (_Jv_JNI_LocalFrame)
304 + size * sizeof (jobject));
306 catch (jthrowable t)
308 env->ex = t;
309 return JNI_ERR;
312 frame->marker = MARK_NONE;
313 frame->size = size;
314 frame->allocated_p = 0;
315 memset (&frame->vec[0], 0, size * sizeof (jobject));
316 frame->next = env->locals;
317 env->locals = frame;
319 return 0;
322 static jint JNICALL
323 _Jv_JNI_PushLocalFrame (JNIEnv *env, jint size)
325 jint r = _Jv_JNI_EnsureLocalCapacity (env, size);
326 if (r < 0)
327 return r;
329 // The new frame is on top.
330 env->locals->marker = MARK_USER;
332 return 0;
335 static jobject JNICALL
336 _Jv_JNI_NewLocalRef (JNIEnv *env, jobject obj)
338 // This seems weird but I think it is correct.
339 obj = unwrap (obj);
341 // Try to find an open slot somewhere in the topmost frame.
342 _Jv_JNI_LocalFrame *frame = env->locals;
343 bool done = false, set = false;
344 for (; frame != NULL && ! done; frame = frame->next)
346 for (int i = 0; i < frame->size; ++i)
348 if (frame->vec[i] == NULL)
350 set = true;
351 done = true;
352 frame->vec[i] = obj;
353 frame->allocated_p = 1;
354 break;
358 // If we found a slot, or if the frame we just searched is the
359 // mark frame, then we are done.
360 if (done || frame == NULL || frame->marker != MARK_NONE)
361 break;
364 if (! set)
366 // No slots, so we allocate a new frame. According to the spec
367 // we could just die here. FIXME: return value.
368 _Jv_JNI_EnsureLocalCapacity (env, 16);
369 // We know the first element of the new frame will be ok.
370 env->locals->vec[0] = obj;
371 env->locals->allocated_p = 1;
374 mark_for_gc (obj, local_ref_table);
375 return obj;
378 static jobject JNICALL
379 _Jv_JNI_PopLocalFrame (JNIEnv *env, jobject result, int stop)
381 _Jv_JNI_LocalFrame *rf = env->locals;
383 bool done = false;
384 while (rf != NULL && ! done)
386 for (int i = 0; i < rf->size; ++i)
387 if (rf->vec[i] != NULL)
388 unmark_for_gc (rf->vec[i], local_ref_table);
390 // If the frame we just freed is the marker frame, we are done.
391 done = (rf->marker == stop);
393 _Jv_JNI_LocalFrame *n = rf->next;
394 // When N==NULL, we've reached the reusable bottom_locals, and we must
395 // not free it. However, we must be sure to clear all its elements.
396 if (n == NULL)
398 if (rf->allocated_p)
399 memset (&rf->vec[0], 0, rf->size * sizeof (jobject));
400 rf->allocated_p = 0;
401 rf = NULL;
402 break;
405 _Jv_Free (rf);
406 rf = n;
409 // Update the local frame information.
410 env->locals = rf;
412 return result == NULL ? NULL : _Jv_JNI_NewLocalRef (env, result);
415 static jobject JNICALL
416 _Jv_JNI_PopLocalFrame (JNIEnv *env, jobject result)
418 return _Jv_JNI_PopLocalFrame (env, result, MARK_USER);
421 // Make sure an array's type is compatible with the type of the
422 // destination.
423 template<typename T>
424 static bool
425 _Jv_JNI_check_types (JNIEnv *env, JArray<T> *array, jclass K)
427 jclass klass = array->getClass()->getComponentType();
428 if (__builtin_expect (klass != K, false))
430 env->ex = new java::lang::IllegalAccessError ();
431 return false;
433 else
434 return true;
437 // Pop a `system' frame from the stack. This is `extern "C"' as it is
438 // used by the compiler.
439 extern "C" void
440 _Jv_JNI_PopSystemFrame (JNIEnv *env)
442 // Only enter slow path when we're not at the bottom, or there have been
443 // allocations. Usually this is false and we can just null out the locals
444 // field.
446 if (__builtin_expect ((env->locals->next
447 || env->locals->allocated_p), false))
448 _Jv_JNI_PopLocalFrame (env, NULL, MARK_SYSTEM);
449 else
450 env->locals = NULL;
452 if (__builtin_expect (env->ex != NULL, false))
454 jthrowable t = env->ex;
455 env->ex = NULL;
456 throw t;
460 template<typename T> T extract_from_jvalue(jvalue const & t);
461 template<> jboolean extract_from_jvalue(jvalue const & jv) { return jv.z; }
462 template<> jbyte extract_from_jvalue(jvalue const & jv) { return jv.b; }
463 template<> jchar extract_from_jvalue(jvalue const & jv) { return jv.c; }
464 template<> jshort extract_from_jvalue(jvalue const & jv) { return jv.s; }
465 template<> jint extract_from_jvalue(jvalue const & jv) { return jv.i; }
466 template<> jlong extract_from_jvalue(jvalue const & jv) { return jv.j; }
467 template<> jfloat extract_from_jvalue(jvalue const & jv) { return jv.f; }
468 template<> jdouble extract_from_jvalue(jvalue const & jv) { return jv.d; }
469 template<> jobject extract_from_jvalue(jvalue const & jv) { return jv.l; }
472 // This function is used from other template functions. It wraps the
473 // return value appropriately; we specialize it so that object returns
474 // are turned into local references.
475 template<typename T>
476 static T
477 wrap_value (JNIEnv *, T value)
479 return value;
482 // This specialization is used for jobject, jclass, jstring, jarray,
483 // etc.
484 template<typename R, typename T>
485 static T *
486 wrap_value (JNIEnv *env, T *value)
488 return (value == NULL
489 ? value
490 : (T *) _Jv_JNI_NewLocalRef (env, (jobject) value));
495 static jint JNICALL
496 _Jv_JNI_GetVersion (JNIEnv *)
498 return JNI_VERSION_1_4;
501 static jclass JNICALL
502 _Jv_JNI_DefineClass (JNIEnv *env, const char *name, jobject loader,
503 const jbyte *buf, jsize bufLen)
507 loader = unwrap (loader);
509 jstring sname = JvNewStringUTF (name);
510 jbyteArray bytes = JvNewByteArray (bufLen);
512 jbyte *elts = elements (bytes);
513 memcpy (elts, buf, bufLen * sizeof (jbyte));
515 java::lang::ClassLoader *l
516 = reinterpret_cast<java::lang::ClassLoader *> (loader);
518 jclass result = l->defineClass (sname, bytes, 0, bufLen);
519 return (jclass) wrap_value (env, result);
521 catch (jthrowable t)
523 env->ex = t;
524 return NULL;
528 static jclass JNICALL
529 _Jv_JNI_FindClass (JNIEnv *env, const char *name)
531 // FIXME: assume that NAME isn't too long.
532 int len = strlen (name);
533 char s[len + 1];
534 for (int i = 0; i <= len; ++i)
535 s[i] = (name[i] == '/') ? '.' : name[i];
537 jclass r = NULL;
540 // This might throw an out of memory exception.
541 jstring n = JvNewStringUTF (s);
543 java::lang::ClassLoader *loader = NULL;
544 if (env->klass != NULL)
545 loader = env->klass->getClassLoaderInternal ();
547 if (loader == NULL)
549 // FIXME: should use getBaseClassLoader, but we don't have that
550 // yet.
551 loader = java::lang::ClassLoader::getSystemClassLoader ();
554 r = loader->loadClass (n);
556 catch (jthrowable t)
558 env->ex = t;
561 return (jclass) wrap_value (env, r);
564 static jclass JNICALL
565 _Jv_JNI_GetSuperclass (JNIEnv *env, jclass clazz)
567 return (jclass) wrap_value (env, unwrap (clazz)->getSuperclass ());
570 static jboolean JNICALL
571 _Jv_JNI_IsAssignableFrom (JNIEnv *, jclass clazz1, jclass clazz2)
573 return unwrap (clazz2)->isAssignableFrom (unwrap (clazz1));
576 static jint JNICALL
577 _Jv_JNI_Throw (JNIEnv *env, jthrowable obj)
579 // We check in case the user did some funky cast.
580 obj = unwrap (obj);
581 JvAssert (obj != NULL && java::lang::Throwable::class$.isInstance (obj));
582 env->ex = obj;
583 return 0;
586 static jint JNICALL
587 _Jv_JNI_ThrowNew (JNIEnv *env, jclass clazz, const char *message)
589 using namespace java::lang::reflect;
591 clazz = unwrap (clazz);
592 JvAssert (java::lang::Throwable::class$.isAssignableFrom (clazz));
594 int r = JNI_OK;
597 JArray<jclass> *argtypes
598 = (JArray<jclass> *) JvNewObjectArray (1, &java::lang::Class::class$,
599 NULL);
601 jclass *elts = elements (argtypes);
602 elts[0] = &java::lang::String::class$;
604 Constructor *cons = clazz->getConstructor (argtypes);
606 jobjectArray values = JvNewObjectArray (1, &java::lang::String::class$,
607 NULL);
608 jobject *velts = elements (values);
609 velts[0] = JvNewStringUTF (message);
611 jobject obj = cons->newInstance (values);
613 env->ex = reinterpret_cast<jthrowable> (obj);
615 catch (jthrowable t)
617 env->ex = t;
618 r = JNI_ERR;
621 return r;
624 static jthrowable JNICALL
625 _Jv_JNI_ExceptionOccurred (JNIEnv *env)
627 return (jthrowable) wrap_value (env, env->ex);
630 static void JNICALL
631 _Jv_JNI_ExceptionDescribe (JNIEnv *env)
633 if (env->ex != NULL)
634 env->ex->printStackTrace();
637 static void JNICALL
638 _Jv_JNI_ExceptionClear (JNIEnv *env)
640 env->ex = NULL;
643 static jboolean JNICALL
644 _Jv_JNI_ExceptionCheck (JNIEnv *env)
646 return env->ex != NULL;
649 static void JNICALL
650 _Jv_JNI_FatalError (JNIEnv *, const char *message)
652 JvFail (message);
657 static jboolean JNICALL
658 _Jv_JNI_IsSameObject (JNIEnv *, jobject obj1, jobject obj2)
660 return unwrap (obj1) == unwrap (obj2);
663 static jobject JNICALL
664 _Jv_JNI_AllocObject (JNIEnv *env, jclass clazz)
666 jobject obj = NULL;
667 using namespace java::lang::reflect;
671 clazz = unwrap (clazz);
672 JvAssert (clazz && ! clazz->isArray ());
673 if (clazz->isInterface() || Modifier::isAbstract(clazz->getModifiers()))
674 env->ex = new java::lang::InstantiationException ();
675 else
676 obj = _Jv_AllocObject (clazz);
678 catch (jthrowable t)
680 env->ex = t;
683 return wrap_value (env, obj);
686 static jclass JNICALL
687 _Jv_JNI_GetObjectClass (JNIEnv *env, jobject obj)
689 obj = unwrap (obj);
690 JvAssert (obj);
691 return (jclass) wrap_value (env, obj->getClass());
694 static jboolean JNICALL
695 _Jv_JNI_IsInstanceOf (JNIEnv *, jobject obj, jclass clazz)
697 return unwrap (clazz)->isInstance(unwrap (obj));
703 // This section concerns method invocation.
706 template<jboolean is_static>
707 static jmethodID JNICALL
708 _Jv_JNI_GetAnyMethodID (JNIEnv *env, jclass clazz,
709 const char *name, const char *sig)
713 clazz = unwrap (clazz);
714 _Jv_InitClass (clazz);
716 _Jv_Utf8Const *name_u = _Jv_makeUtf8Const ((char *) name, -1);
718 // FIXME: assume that SIG isn't too long.
719 int len = strlen (sig);
720 char s[len + 1];
721 for (int i = 0; i <= len; ++i)
722 s[i] = (sig[i] == '/') ? '.' : sig[i];
723 _Jv_Utf8Const *sig_u = _Jv_makeUtf8Const ((char *) s, -1);
725 JvAssert (! clazz->isPrimitive());
727 using namespace java::lang::reflect;
729 while (clazz != NULL)
731 jint count = JvNumMethods (clazz);
732 jmethodID meth = JvGetFirstMethod (clazz);
734 for (jint i = 0; i < count; ++i)
736 if (((is_static && Modifier::isStatic (meth->accflags))
737 || (! is_static && ! Modifier::isStatic (meth->accflags)))
738 && _Jv_equalUtf8Consts (meth->name, name_u)
739 && _Jv_equalUtf8Consts (meth->signature, sig_u))
740 return meth;
742 meth = meth->getNextMethod();
745 clazz = clazz->getSuperclass ();
748 java::lang::StringBuffer *name_sig =
749 new java::lang::StringBuffer (JvNewStringUTF (name));
750 name_sig->append ((jchar) ' ')->append (JvNewStringUTF (s));
751 env->ex = new java::lang::NoSuchMethodError (name_sig->toString ());
753 catch (jthrowable t)
755 env->ex = t;
758 return NULL;
761 // This is a helper function which turns a va_list into an array of
762 // `jvalue's. It needs signature information in order to do its work.
763 // The array of values must already be allocated.
764 static void
765 array_from_valist (jvalue *values, JArray<jclass> *arg_types, va_list vargs)
767 jclass *arg_elts = elements (arg_types);
768 for (int i = 0; i < arg_types->length; ++i)
770 // Here we assume that sizeof(int) >= sizeof(jint), because we
771 // use `int' when decoding the varargs. Likewise for
772 // float, and double. Also we assume that sizeof(jlong) >=
773 // sizeof(int), i.e. that jlong values are not further
774 // promoted.
775 JvAssert (sizeof (int) >= sizeof (jint));
776 JvAssert (sizeof (jlong) >= sizeof (int));
777 JvAssert (sizeof (double) >= sizeof (jfloat));
778 JvAssert (sizeof (double) >= sizeof (jdouble));
779 if (arg_elts[i] == JvPrimClass (byte))
780 values[i].b = (jbyte) va_arg (vargs, int);
781 else if (arg_elts[i] == JvPrimClass (short))
782 values[i].s = (jshort) va_arg (vargs, int);
783 else if (arg_elts[i] == JvPrimClass (int))
784 values[i].i = (jint) va_arg (vargs, int);
785 else if (arg_elts[i] == JvPrimClass (long))
786 values[i].j = (jlong) va_arg (vargs, jlong);
787 else if (arg_elts[i] == JvPrimClass (float))
788 values[i].f = (jfloat) va_arg (vargs, double);
789 else if (arg_elts[i] == JvPrimClass (double))
790 values[i].d = (jdouble) va_arg (vargs, double);
791 else if (arg_elts[i] == JvPrimClass (boolean))
792 values[i].z = (jboolean) va_arg (vargs, int);
793 else if (arg_elts[i] == JvPrimClass (char))
794 values[i].c = (jchar) va_arg (vargs, int);
795 else
797 // An object.
798 values[i].l = unwrap (va_arg (vargs, jobject));
803 // This can call any sort of method: virtual, "nonvirtual", static, or
804 // constructor.
805 template<typename T, invocation_type style>
806 static T JNICALL
807 _Jv_JNI_CallAnyMethodV (JNIEnv *env, jobject obj, jclass klass,
808 jmethodID id, va_list vargs)
810 obj = unwrap (obj);
811 klass = unwrap (klass);
813 jclass decl_class = klass ? klass : obj->getClass ();
814 JvAssert (decl_class != NULL);
816 jclass return_type;
817 JArray<jclass> *arg_types;
821 _Jv_GetTypesFromSignature (id, decl_class,
822 &arg_types, &return_type);
824 jvalue args[arg_types->length];
825 array_from_valist (args, arg_types, vargs);
827 // For constructors we need to pass the Class we are instantiating.
828 if (style == constructor)
829 return_type = klass;
831 jvalue result;
832 _Jv_CallAnyMethodA (obj, return_type, id,
833 style == constructor,
834 style == normal,
835 arg_types, args, &result);
837 return wrap_value (env, extract_from_jvalue<T>(result));
839 catch (jthrowable t)
841 env->ex = t;
844 return wrap_value (env, (T) 0);
847 template<typename T, invocation_type style>
848 static T JNICALL
849 _Jv_JNI_CallAnyMethod (JNIEnv *env, jobject obj, jclass klass,
850 jmethodID method, ...)
852 va_list args;
853 T result;
855 va_start (args, method);
856 result = _Jv_JNI_CallAnyMethodV<T, style> (env, obj, klass, method, args);
857 va_end (args);
859 return result;
862 template<typename T, invocation_type style>
863 static T JNICALL
864 _Jv_JNI_CallAnyMethodA (JNIEnv *env, jobject obj, jclass klass,
865 jmethodID id, jvalue *args)
867 obj = unwrap (obj);
868 klass = unwrap (klass);
870 jclass decl_class = klass ? klass : obj->getClass ();
871 JvAssert (decl_class != NULL);
873 jclass return_type;
874 JArray<jclass> *arg_types;
877 _Jv_GetTypesFromSignature (id, decl_class,
878 &arg_types, &return_type);
880 // For constructors we need to pass the Class we are instantiating.
881 if (style == constructor)
882 return_type = klass;
884 // Unwrap arguments as required. Eww.
885 jclass *type_elts = elements (arg_types);
886 jvalue arg_copy[arg_types->length];
887 for (int i = 0; i < arg_types->length; ++i)
889 if (type_elts[i]->isPrimitive ())
890 arg_copy[i] = args[i];
891 else
892 arg_copy[i].l = unwrap (args[i].l);
895 jvalue result;
896 _Jv_CallAnyMethodA (obj, return_type, id,
897 style == constructor,
898 style == normal,
899 arg_types, arg_copy, &result);
901 return wrap_value (env, extract_from_jvalue<T>(result));
903 catch (jthrowable t)
905 env->ex = t;
908 return wrap_value (env, (T) 0);
911 template<invocation_type style>
912 static void JNICALL
913 _Jv_JNI_CallAnyVoidMethodV (JNIEnv *env, jobject obj, jclass klass,
914 jmethodID id, va_list vargs)
916 obj = unwrap (obj);
917 klass = unwrap (klass);
919 jclass decl_class = klass ? klass : obj->getClass ();
920 JvAssert (decl_class != NULL);
922 jclass return_type;
923 JArray<jclass> *arg_types;
926 _Jv_GetTypesFromSignature (id, decl_class,
927 &arg_types, &return_type);
929 jvalue args[arg_types->length];
930 array_from_valist (args, arg_types, vargs);
932 // For constructors we need to pass the Class we are instantiating.
933 if (style == constructor)
934 return_type = klass;
936 _Jv_CallAnyMethodA (obj, return_type, id,
937 style == constructor,
938 style == normal,
939 arg_types, args, NULL);
941 catch (jthrowable t)
943 env->ex = t;
947 template<invocation_type style>
948 static void JNICALL
949 _Jv_JNI_CallAnyVoidMethod (JNIEnv *env, jobject obj, jclass klass,
950 jmethodID method, ...)
952 va_list args;
954 va_start (args, method);
955 _Jv_JNI_CallAnyVoidMethodV<style> (env, obj, klass, method, args);
956 va_end (args);
959 template<invocation_type style>
960 static void JNICALL
961 _Jv_JNI_CallAnyVoidMethodA (JNIEnv *env, jobject obj, jclass klass,
962 jmethodID id, jvalue *args)
964 jclass decl_class = klass ? klass : obj->getClass ();
965 JvAssert (decl_class != NULL);
967 jclass return_type;
968 JArray<jclass> *arg_types;
971 _Jv_GetTypesFromSignature (id, decl_class,
972 &arg_types, &return_type);
974 // Unwrap arguments as required. Eww.
975 jclass *type_elts = elements (arg_types);
976 jvalue arg_copy[arg_types->length];
977 for (int i = 0; i < arg_types->length; ++i)
979 if (type_elts[i]->isPrimitive ())
980 arg_copy[i] = args[i];
981 else
982 arg_copy[i].l = unwrap (args[i].l);
985 _Jv_CallAnyMethodA (obj, return_type, id,
986 style == constructor,
987 style == normal,
988 arg_types, args, NULL);
990 catch (jthrowable t)
992 env->ex = t;
996 // Functions with this signature are used to implement functions in
997 // the CallMethod family.
998 template<typename T>
999 static T JNICALL
1000 _Jv_JNI_CallMethodV (JNIEnv *env, jobject obj,
1001 jmethodID id, va_list args)
1003 return _Jv_JNI_CallAnyMethodV<T, normal> (env, obj, NULL, id, args);
1006 // Functions with this signature are used to implement functions in
1007 // the CallMethod family.
1008 template<typename T>
1009 static T JNICALL
1010 _Jv_JNI_CallMethod (JNIEnv *env, jobject obj, jmethodID id, ...)
1012 va_list args;
1013 T result;
1015 va_start (args, id);
1016 result = _Jv_JNI_CallAnyMethodV<T, normal> (env, obj, NULL, id, args);
1017 va_end (args);
1019 return result;
1022 // Functions with this signature are used to implement functions in
1023 // the CallMethod family.
1024 template<typename T>
1025 static T JNICALL
1026 _Jv_JNI_CallMethodA (JNIEnv *env, jobject obj,
1027 jmethodID id, jvalue *args)
1029 return _Jv_JNI_CallAnyMethodA<T, normal> (env, obj, NULL, id, args);
1032 static void JNICALL
1033 _Jv_JNI_CallVoidMethodV (JNIEnv *env, jobject obj,
1034 jmethodID id, va_list args)
1036 _Jv_JNI_CallAnyVoidMethodV<normal> (env, obj, NULL, id, args);
1039 static void JNICALL
1040 _Jv_JNI_CallVoidMethod (JNIEnv *env, jobject obj, jmethodID id, ...)
1042 va_list args;
1044 va_start (args, id);
1045 _Jv_JNI_CallAnyVoidMethodV<normal> (env, obj, NULL, id, args);
1046 va_end (args);
1049 static void JNICALL
1050 _Jv_JNI_CallVoidMethodA (JNIEnv *env, jobject obj,
1051 jmethodID id, jvalue *args)
1053 _Jv_JNI_CallAnyVoidMethodA<normal> (env, obj, NULL, id, args);
1056 // Functions with this signature are used to implement functions in
1057 // the CallStaticMethod family.
1058 template<typename T>
1059 static T JNICALL
1060 _Jv_JNI_CallStaticMethodV (JNIEnv *env, jclass klass,
1061 jmethodID id, va_list args)
1063 JvAssert (((id->accflags) & java::lang::reflect::Modifier::STATIC));
1064 JvAssert (java::lang::Class::class$.isInstance (unwrap (klass)));
1066 return _Jv_JNI_CallAnyMethodV<T, static_type> (env, NULL, klass, id, args);
1069 // Functions with this signature are used to implement functions in
1070 // the CallStaticMethod family.
1071 template<typename T>
1072 static T JNICALL
1073 _Jv_JNI_CallStaticMethod (JNIEnv *env, jclass klass,
1074 jmethodID id, ...)
1076 va_list args;
1077 T result;
1079 JvAssert (((id->accflags) & java::lang::reflect::Modifier::STATIC));
1080 JvAssert (java::lang::Class::class$.isInstance (unwrap (klass)));
1082 va_start (args, id);
1083 result = _Jv_JNI_CallAnyMethodV<T, static_type> (env, NULL, klass,
1084 id, args);
1085 va_end (args);
1087 return result;
1090 // Functions with this signature are used to implement functions in
1091 // the CallStaticMethod family.
1092 template<typename T>
1093 static T JNICALL
1094 _Jv_JNI_CallStaticMethodA (JNIEnv *env, jclass klass, jmethodID id,
1095 jvalue *args)
1097 JvAssert (((id->accflags) & java::lang::reflect::Modifier::STATIC));
1098 JvAssert (java::lang::Class::class$.isInstance (unwrap (klass)));
1100 return _Jv_JNI_CallAnyMethodA<T, static_type> (env, NULL, klass, id, args);
1103 static void JNICALL
1104 _Jv_JNI_CallStaticVoidMethodV (JNIEnv *env, jclass klass,
1105 jmethodID id, va_list args)
1107 _Jv_JNI_CallAnyVoidMethodV<static_type> (env, NULL, klass, id, args);
1110 static void JNICALL
1111 _Jv_JNI_CallStaticVoidMethod (JNIEnv *env, jclass klass,
1112 jmethodID id, ...)
1114 va_list args;
1116 va_start (args, id);
1117 _Jv_JNI_CallAnyVoidMethodV<static_type> (env, NULL, klass, id, args);
1118 va_end (args);
1121 static void JNICALL
1122 _Jv_JNI_CallStaticVoidMethodA (JNIEnv *env, jclass klass,
1123 jmethodID id, jvalue *args)
1125 _Jv_JNI_CallAnyVoidMethodA<static_type> (env, NULL, klass, id, args);
1128 static jobject JNICALL
1129 _Jv_JNI_NewObjectV (JNIEnv *env, jclass klass,
1130 jmethodID id, va_list args)
1132 JvAssert (klass && ! klass->isArray ());
1133 JvAssert (! strcmp (id->name->chars(), "<init>")
1134 && id->signature->len() > 2
1135 && id->signature->chars()[0] == '('
1136 && ! strcmp (&id->signature->chars()[id->signature->len() - 2],
1137 ")V"));
1139 return _Jv_JNI_CallAnyMethodV<jobject, constructor> (env, NULL, klass,
1140 id, args);
1143 static jobject JNICALL
1144 _Jv_JNI_NewObject (JNIEnv *env, jclass klass, jmethodID id, ...)
1146 JvAssert (klass && ! klass->isArray ());
1147 JvAssert (! strcmp (id->name->chars(), "<init>")
1148 && id->signature->len() > 2
1149 && id->signature->chars()[0] == '('
1150 && ! strcmp (&id->signature->chars()[id->signature->len() - 2],
1151 ")V"));
1153 va_list args;
1154 jobject result;
1156 va_start (args, id);
1157 result = _Jv_JNI_CallAnyMethodV<jobject, constructor> (env, NULL, klass,
1158 id, args);
1159 va_end (args);
1161 return result;
1164 static jobject JNICALL
1165 _Jv_JNI_NewObjectA (JNIEnv *env, jclass klass, jmethodID id,
1166 jvalue *args)
1168 JvAssert (klass && ! klass->isArray ());
1169 JvAssert (! strcmp (id->name->chars(), "<init>")
1170 && id->signature->len() > 2
1171 && id->signature->chars()[0] == '('
1172 && ! strcmp (&id->signature->chars()[id->signature->len() - 2],
1173 ")V"));
1175 return _Jv_JNI_CallAnyMethodA<jobject, constructor> (env, NULL, klass,
1176 id, args);
1181 template<typename T>
1182 static T JNICALL
1183 _Jv_JNI_GetField (JNIEnv *env, jobject obj, jfieldID field)
1185 obj = unwrap (obj);
1186 JvAssert (obj);
1187 T *ptr = (T *) ((char *) obj + field->getOffset ());
1188 return wrap_value (env, *ptr);
1191 template<typename T>
1192 static void JNICALL
1193 _Jv_JNI_SetField (JNIEnv *, jobject obj, jfieldID field, T value)
1195 obj = unwrap (obj);
1196 value = unwrap (value);
1198 JvAssert (obj);
1199 T *ptr = (T *) ((char *) obj + field->getOffset ());
1200 *ptr = value;
1203 template<jboolean is_static>
1204 static jfieldID JNICALL
1205 _Jv_JNI_GetAnyFieldID (JNIEnv *env, jclass clazz,
1206 const char *name, const char *sig)
1210 clazz = unwrap (clazz);
1212 _Jv_InitClass (clazz);
1214 _Jv_Utf8Const *a_name = _Jv_makeUtf8Const ((char *) name, -1);
1216 // FIXME: assume that SIG isn't too long.
1217 int len = strlen (sig);
1218 char s[len + 1];
1219 for (int i = 0; i <= len; ++i)
1220 s[i] = (sig[i] == '/') ? '.' : sig[i];
1221 java::lang::ClassLoader *loader = clazz->getClassLoaderInternal ();
1222 jclass field_class = _Jv_FindClassFromSignature ((char *) s, loader);
1223 if (! field_class)
1224 throw new java::lang::ClassNotFoundException(JvNewStringUTF(s));
1226 while (clazz != NULL)
1228 // We acquire the class lock so that fields aren't resolved
1229 // while we are running.
1230 JvSynchronize sync (clazz);
1232 jint count = (is_static
1233 ? JvNumStaticFields (clazz)
1234 : JvNumInstanceFields (clazz));
1235 jfieldID field = (is_static
1236 ? JvGetFirstStaticField (clazz)
1237 : JvGetFirstInstanceField (clazz));
1238 for (jint i = 0; i < count; ++i)
1240 _Jv_Utf8Const *f_name = field->getNameUtf8Const(clazz);
1242 // The field might be resolved or it might not be. It
1243 // is much simpler to always resolve it.
1244 _Jv_Linker::resolve_field (field, loader);
1245 if (_Jv_equalUtf8Consts (f_name, a_name)
1246 && field->getClass() == field_class)
1247 return field;
1249 field = field->getNextField ();
1252 clazz = clazz->getSuperclass ();
1255 env->ex = new java::lang::NoSuchFieldError ();
1257 catch (jthrowable t)
1259 env->ex = t;
1261 return NULL;
1264 template<typename T>
1265 static T JNICALL
1266 _Jv_JNI_GetStaticField (JNIEnv *env, jclass, jfieldID field)
1268 T *ptr = (T *) field->u.addr;
1269 return wrap_value (env, *ptr);
1272 template<typename T>
1273 static void JNICALL
1274 _Jv_JNI_SetStaticField (JNIEnv *, jclass, jfieldID field, T value)
1276 value = unwrap (value);
1277 T *ptr = (T *) field->u.addr;
1278 *ptr = value;
1281 static jstring JNICALL
1282 _Jv_JNI_NewString (JNIEnv *env, const jchar *unichars, jsize len)
1286 jstring r = _Jv_NewString (unichars, len);
1287 return (jstring) wrap_value (env, r);
1289 catch (jthrowable t)
1291 env->ex = t;
1292 return NULL;
1296 static jsize JNICALL
1297 _Jv_JNI_GetStringLength (JNIEnv *, jstring string)
1299 return unwrap (string)->length();
1302 static const jchar * JNICALL
1303 _Jv_JNI_GetStringChars (JNIEnv *, jstring string, jboolean *isCopy)
1305 string = unwrap (string);
1306 jchar *result = _Jv_GetStringChars (string);
1307 mark_for_gc (string, global_ref_table);
1308 if (isCopy)
1309 *isCopy = false;
1310 return (const jchar *) result;
1313 static void JNICALL
1314 _Jv_JNI_ReleaseStringChars (JNIEnv *, jstring string, const jchar *)
1316 unmark_for_gc (unwrap (string), global_ref_table);
1319 static jstring JNICALL
1320 _Jv_JNI_NewStringUTF (JNIEnv *env, const char *bytes)
1324 jstring result = JvNewStringUTF (bytes);
1325 return (jstring) wrap_value (env, result);
1327 catch (jthrowable t)
1329 env->ex = t;
1330 return NULL;
1334 static jsize JNICALL
1335 _Jv_JNI_GetStringUTFLength (JNIEnv *, jstring string)
1337 return JvGetStringUTFLength (unwrap (string));
1340 static const char * JNICALL
1341 _Jv_JNI_GetStringUTFChars (JNIEnv *env, jstring string,
1342 jboolean *isCopy)
1346 string = unwrap (string);
1347 if (string == NULL)
1348 return NULL;
1349 jsize len = JvGetStringUTFLength (string);
1350 char *r = (char *) _Jv_Malloc (len + 1);
1351 JvGetStringUTFRegion (string, 0, string->length(), r);
1352 r[len] = '\0';
1354 if (isCopy)
1355 *isCopy = true;
1357 return (const char *) r;
1359 catch (jthrowable t)
1361 env->ex = t;
1362 return NULL;
1366 static void JNICALL
1367 _Jv_JNI_ReleaseStringUTFChars (JNIEnv *, jstring, const char *utf)
1369 _Jv_Free ((void *) utf);
1372 static void JNICALL
1373 _Jv_JNI_GetStringRegion (JNIEnv *env, jstring string, jsize start,
1374 jsize len, jchar *buf)
1376 string = unwrap (string);
1377 jchar *result = _Jv_GetStringChars (string);
1378 if (start < 0 || start > string->length ()
1379 || len < 0 || start + len > string->length ())
1383 env->ex = new java::lang::StringIndexOutOfBoundsException ();
1385 catch (jthrowable t)
1387 env->ex = t;
1390 else
1391 memcpy (buf, &result[start], len * sizeof (jchar));
1394 static void JNICALL
1395 _Jv_JNI_GetStringUTFRegion (JNIEnv *env, jstring str, jsize start,
1396 jsize len, char *buf)
1398 str = unwrap (str);
1400 if (start < 0 || start > str->length ()
1401 || len < 0 || start + len > str->length ())
1405 env->ex = new java::lang::StringIndexOutOfBoundsException ();
1407 catch (jthrowable t)
1409 env->ex = t;
1412 else
1413 _Jv_GetStringUTFRegion (str, start, len, buf);
1416 static const jchar * JNICALL
1417 _Jv_JNI_GetStringCritical (JNIEnv *, jstring str, jboolean *isCopy)
1419 jchar *result = _Jv_GetStringChars (unwrap (str));
1420 if (isCopy)
1421 *isCopy = false;
1422 return result;
1425 static void JNICALL
1426 _Jv_JNI_ReleaseStringCritical (JNIEnv *, jstring, const jchar *)
1428 // Nothing.
1431 static jsize JNICALL
1432 _Jv_JNI_GetArrayLength (JNIEnv *, jarray array)
1434 return unwrap (array)->length;
1437 static jobjectArray JNICALL
1438 _Jv_JNI_NewObjectArray (JNIEnv *env, jsize length,
1439 jclass elementClass, jobject init)
1443 elementClass = unwrap (elementClass);
1444 init = unwrap (init);
1446 _Jv_CheckCast (elementClass, init);
1447 jarray result = JvNewObjectArray (length, elementClass, init);
1448 return (jobjectArray) wrap_value (env, result);
1450 catch (jthrowable t)
1452 env->ex = t;
1453 return NULL;
1457 static jobject JNICALL
1458 _Jv_JNI_GetObjectArrayElement (JNIEnv *env, jobjectArray array,
1459 jsize index)
1461 if ((unsigned) index >= (unsigned) array->length)
1462 _Jv_ThrowBadArrayIndex (index);
1463 jobject *elts = elements (unwrap (array));
1464 return wrap_value (env, elts[index]);
1467 static void JNICALL
1468 _Jv_JNI_SetObjectArrayElement (JNIEnv *env, jobjectArray array,
1469 jsize index, jobject value)
1473 array = unwrap (array);
1474 value = unwrap (value);
1476 _Jv_CheckArrayStore (array, value);
1477 if ((unsigned) index >= (unsigned) array->length)
1478 _Jv_ThrowBadArrayIndex (index);
1479 jobject *elts = elements (array);
1480 elts[index] = value;
1482 catch (jthrowable t)
1484 env->ex = t;
1488 template<typename T, jclass K>
1489 static JArray<T> * JNICALL
1490 _Jv_JNI_NewPrimitiveArray (JNIEnv *env, jsize length)
1494 return (JArray<T> *) wrap_value (env, _Jv_NewPrimArray (K, length));
1496 catch (jthrowable t)
1498 env->ex = t;
1499 return NULL;
1503 template<typename T, jclass K>
1504 static T * JNICALL
1505 _Jv_JNI_GetPrimitiveArrayElements (JNIEnv *env, JArray<T> *array,
1506 jboolean *isCopy)
1508 array = unwrap (array);
1509 if (! _Jv_JNI_check_types (env, array, K))
1510 return NULL;
1511 T *elts = elements (array);
1512 if (isCopy)
1514 // We elect never to copy.
1515 *isCopy = false;
1517 mark_for_gc (array, global_ref_table);
1518 return elts;
1521 template<typename T, jclass K>
1522 static void JNICALL
1523 _Jv_JNI_ReleasePrimitiveArrayElements (JNIEnv *env, JArray<T> *array,
1524 T *, jint /* mode */)
1526 array = unwrap (array);
1527 _Jv_JNI_check_types (env, array, K);
1528 // Note that we ignore MODE. We can do this because we never copy
1529 // the array elements. My reading of the JNI documentation is that
1530 // this is an option for the implementor.
1531 unmark_for_gc (array, global_ref_table);
1534 template<typename T, jclass K>
1535 static void JNICALL
1536 _Jv_JNI_GetPrimitiveArrayRegion (JNIEnv *env, JArray<T> *array,
1537 jsize start, jsize len,
1538 T *buf)
1540 array = unwrap (array);
1541 if (! _Jv_JNI_check_types (env, array, K))
1542 return;
1544 // The cast to unsigned lets us save a comparison.
1545 if (start < 0 || len < 0
1546 || (unsigned long) (start + len) > (unsigned long) array->length)
1550 // FIXME: index.
1551 env->ex = new java::lang::ArrayIndexOutOfBoundsException ();
1553 catch (jthrowable t)
1555 // Could have thown out of memory error.
1556 env->ex = t;
1559 else
1561 T *elts = elements (array) + start;
1562 memcpy (buf, elts, len * sizeof (T));
1566 template<typename T, jclass K>
1567 static void JNICALL
1568 _Jv_JNI_SetPrimitiveArrayRegion (JNIEnv *env, JArray<T> *array,
1569 jsize start, jsize len, T *buf)
1571 array = unwrap (array);
1572 if (! _Jv_JNI_check_types (env, array, K))
1573 return;
1575 // The cast to unsigned lets us save a comparison.
1576 if (start < 0 || len < 0
1577 || (unsigned long) (start + len) > (unsigned long) array->length)
1581 // FIXME: index.
1582 env->ex = new java::lang::ArrayIndexOutOfBoundsException ();
1584 catch (jthrowable t)
1586 env->ex = t;
1589 else
1591 T *elts = elements (array) + start;
1592 memcpy (elts, buf, len * sizeof (T));
1596 static void * JNICALL
1597 _Jv_JNI_GetPrimitiveArrayCritical (JNIEnv *, jarray array,
1598 jboolean *isCopy)
1600 array = unwrap (array);
1601 // FIXME: does this work?
1602 jclass klass = array->getClass()->getComponentType();
1603 JvAssert (klass->isPrimitive ());
1604 char *r = _Jv_GetArrayElementFromElementType (array, klass);
1605 if (isCopy)
1606 *isCopy = false;
1607 return r;
1610 static void JNICALL
1611 _Jv_JNI_ReleasePrimitiveArrayCritical (JNIEnv *, jarray, void *, jint)
1613 // Nothing.
1616 static jint JNICALL
1617 _Jv_JNI_MonitorEnter (JNIEnv *env, jobject obj)
1621 _Jv_MonitorEnter (unwrap (obj));
1622 return 0;
1624 catch (jthrowable t)
1626 env->ex = t;
1628 return JNI_ERR;
1631 static jint JNICALL
1632 _Jv_JNI_MonitorExit (JNIEnv *env, jobject obj)
1636 _Jv_MonitorExit (unwrap (obj));
1637 return 0;
1639 catch (jthrowable t)
1641 env->ex = t;
1643 return JNI_ERR;
1646 // JDK 1.2
1647 jobject JNICALL
1648 _Jv_JNI_ToReflectedField (JNIEnv *env, jclass cls, jfieldID fieldID,
1649 jboolean)
1653 cls = unwrap (cls);
1654 java::lang::reflect::Field *field = new java::lang::reflect::Field();
1655 field->declaringClass = cls;
1656 field->offset = (char*) fieldID - (char *) cls->fields;
1657 field->name = _Jv_NewStringUtf8Const (fieldID->getNameUtf8Const (cls));
1658 return wrap_value (env, field);
1660 catch (jthrowable t)
1662 env->ex = t;
1664 return NULL;
1667 // JDK 1.2
1668 static jfieldID JNICALL
1669 _Jv_JNI_FromReflectedField (JNIEnv *, jobject f)
1671 using namespace java::lang::reflect;
1673 f = unwrap (f);
1674 Field *field = reinterpret_cast<Field *> (f);
1675 return _Jv_FromReflectedField (field);
1678 jobject JNICALL
1679 _Jv_JNI_ToReflectedMethod (JNIEnv *env, jclass klass, jmethodID id,
1680 jboolean)
1682 using namespace java::lang::reflect;
1684 jobject result = NULL;
1685 klass = unwrap (klass);
1689 if (_Jv_equalUtf8Consts (id->name, init_name))
1691 // A constructor.
1692 Constructor *cons = new Constructor ();
1693 cons->offset = (char *) id - (char *) &klass->methods;
1694 cons->declaringClass = klass;
1695 result = cons;
1697 else
1699 Method *meth = new Method ();
1700 meth->offset = (char *) id - (char *) &klass->methods;
1701 meth->declaringClass = klass;
1702 result = meth;
1705 catch (jthrowable t)
1707 env->ex = t;
1710 return wrap_value (env, result);
1713 static jmethodID JNICALL
1714 _Jv_JNI_FromReflectedMethod (JNIEnv *, jobject method)
1716 using namespace java::lang::reflect;
1717 method = unwrap (method);
1718 if (Method::class$.isInstance (method))
1719 return _Jv_FromReflectedMethod (reinterpret_cast<Method *> (method));
1720 return
1721 _Jv_FromReflectedConstructor (reinterpret_cast<Constructor *> (method));
1724 // JDK 1.2.
1725 jweak JNICALL
1726 _Jv_JNI_NewWeakGlobalRef (JNIEnv *env, jobject obj)
1728 using namespace gnu::gcj::runtime;
1729 JNIWeakRef *ref = NULL;
1733 // This seems weird but I think it is correct.
1734 obj = unwrap (obj);
1735 ref = new JNIWeakRef (obj);
1736 mark_for_gc (ref, global_ref_table);
1738 catch (jthrowable t)
1740 env->ex = t;
1743 return reinterpret_cast<jweak> (ref);
1746 void JNICALL
1747 _Jv_JNI_DeleteWeakGlobalRef (JNIEnv *, jweak obj)
1749 using namespace gnu::gcj::runtime;
1750 JNIWeakRef *ref = reinterpret_cast<JNIWeakRef *> (obj);
1751 unmark_for_gc (ref, global_ref_table);
1752 ref->clear ();
1757 // Direct byte buffers.
1759 static jobject JNICALL
1760 _Jv_JNI_NewDirectByteBuffer (JNIEnv *, void *address, jlong length)
1762 using namespace gnu::gcj;
1763 using namespace java::nio;
1764 return new DirectByteBufferImpl$ReadWrite
1765 (reinterpret_cast<RawData *> (address), length);
1768 static void * JNICALL
1769 _Jv_JNI_GetDirectBufferAddress (JNIEnv *, jobject buffer)
1771 using namespace java::nio;
1772 if (! _Jv_IsInstanceOf (buffer, &Buffer::class$))
1773 return NULL;
1774 Buffer *tmp = static_cast<Buffer *> (buffer);
1775 return reinterpret_cast<void *> (tmp->address);
1778 static jlong JNICALL
1779 _Jv_JNI_GetDirectBufferCapacity (JNIEnv *, jobject buffer)
1781 using namespace java::nio;
1782 if (! _Jv_IsInstanceOf (buffer, &Buffer::class$))
1783 return -1;
1784 Buffer *tmp = static_cast<Buffer *> (buffer);
1785 if (tmp->address == NULL)
1786 return -1;
1787 return tmp->capacity();
1792 // Hash table of native methods.
1793 static JNINativeMethod *nathash;
1794 // Number of slots used.
1795 static int nathash_count = 0;
1796 // Number of slots available. Must be power of 2.
1797 static int nathash_size = 0;
1799 #define DELETED_ENTRY ((char *) (~0))
1801 // Compute a hash value for a native method descriptor.
1802 static int
1803 hash (const JNINativeMethod *method)
1805 char *ptr;
1806 int hash = 0;
1808 ptr = method->name;
1809 while (*ptr)
1810 hash = (31 * hash) + *ptr++;
1812 ptr = method->signature;
1813 while (*ptr)
1814 hash = (31 * hash) + *ptr++;
1816 return hash;
1819 // Find the slot where a native method goes.
1820 static JNINativeMethod *
1821 nathash_find_slot (const JNINativeMethod *method)
1823 jint h = hash (method);
1824 int step = (h ^ (h >> 16)) | 1;
1825 int w = h & (nathash_size - 1);
1826 int del = -1;
1828 for (;;)
1830 JNINativeMethod *slotp = &nathash[w];
1831 if (slotp->name == NULL)
1833 if (del >= 0)
1834 return &nathash[del];
1835 else
1836 return slotp;
1838 else if (slotp->name == DELETED_ENTRY)
1839 del = w;
1840 else if (! strcmp (slotp->name, method->name)
1841 && ! strcmp (slotp->signature, method->signature))
1842 return slotp;
1843 w = (w + step) & (nathash_size - 1);
1847 // Find a method. Return NULL if it isn't in the hash table.
1848 static void *
1849 nathash_find (JNINativeMethod *method)
1851 if (nathash == NULL)
1852 return NULL;
1853 JNINativeMethod *slot = nathash_find_slot (method);
1854 if (slot->name == NULL || slot->name == DELETED_ENTRY)
1855 return NULL;
1856 return slot->fnPtr;
1859 static void
1860 natrehash ()
1862 if (nathash == NULL)
1864 nathash_size = 1024;
1865 nathash =
1866 (JNINativeMethod *) _Jv_AllocBytes (nathash_size
1867 * sizeof (JNINativeMethod));
1869 else
1871 int savesize = nathash_size;
1872 JNINativeMethod *savehash = nathash;
1873 nathash_size *= 2;
1874 nathash =
1875 (JNINativeMethod *) _Jv_AllocBytes (nathash_size
1876 * sizeof (JNINativeMethod));
1878 for (int i = 0; i < savesize; ++i)
1880 if (savehash[i].name != NULL && savehash[i].name != DELETED_ENTRY)
1882 JNINativeMethod *slot = nathash_find_slot (&savehash[i]);
1883 *slot = savehash[i];
1889 static void
1890 nathash_add (const JNINativeMethod *method)
1892 if (3 * nathash_count >= 2 * nathash_size)
1893 natrehash ();
1894 JNINativeMethod *slot = nathash_find_slot (method);
1895 // If the slot has a real entry in it, then there is no work to do.
1896 if (slot->name != NULL && slot->name != DELETED_ENTRY)
1897 return;
1898 // FIXME
1899 slot->name = strdup (method->name);
1900 // This was already strduped in _Jv_JNI_RegisterNatives.
1901 slot->signature = method->signature;
1902 slot->fnPtr = method->fnPtr;
1905 static jint JNICALL
1906 _Jv_JNI_RegisterNatives (JNIEnv *env, jclass klass,
1907 const JNINativeMethod *methods,
1908 jint nMethods)
1910 // Synchronize while we do the work. This must match
1911 // synchronization in some other functions that manipulate or use
1912 // the nathash table.
1913 JvSynchronize sync (global_ref_table);
1915 JNINativeMethod dottedMethod;
1917 // Look at each descriptor given us, and find the corresponding
1918 // method in the class.
1919 for (int j = 0; j < nMethods; ++j)
1921 bool found = false;
1923 _Jv_Method *imeths = JvGetFirstMethod (klass);
1924 for (int i = 0; i < JvNumMethods (klass); ++i)
1926 _Jv_Method *self = &imeths[i];
1928 // Copy this JNINativeMethod and do a slash to dot
1929 // conversion on the signature.
1930 dottedMethod.name = methods[j].name;
1931 dottedMethod.signature = strdup (methods[j].signature);
1932 dottedMethod.fnPtr = methods[j].fnPtr;
1933 char *c = dottedMethod.signature;
1934 while (*c)
1936 if (*c == '/')
1937 *c = '.';
1938 c++;
1941 if (! strcmp (self->name->chars (), dottedMethod.name)
1942 && ! strcmp (self->signature->chars (), dottedMethod.signature))
1944 if (! (self->accflags & java::lang::reflect::Modifier::NATIVE))
1945 break;
1947 // Found a match that is native.
1948 found = true;
1949 nathash_add (&dottedMethod);
1951 break;
1955 if (! found)
1957 jstring m = JvNewStringUTF (methods[j].name);
1960 env->ex = new java::lang::NoSuchMethodError (m);
1962 catch (jthrowable t)
1964 env->ex = t;
1966 return JNI_ERR;
1970 return JNI_OK;
1973 static jint JNICALL
1974 _Jv_JNI_UnregisterNatives (JNIEnv *, jclass)
1976 // FIXME -- we could implement this.
1977 return JNI_ERR;
1982 // Add a character to the buffer, encoding properly.
1983 static void
1984 add_char (char *buf, jchar c, int *here)
1986 if (c == '_')
1988 buf[(*here)++] = '_';
1989 buf[(*here)++] = '1';
1991 else if (c == ';')
1993 buf[(*here)++] = '_';
1994 buf[(*here)++] = '2';
1996 else if (c == '[')
1998 buf[(*here)++] = '_';
1999 buf[(*here)++] = '3';
2002 // Also check for `.' here because we might be passed an internal
2003 // qualified class name like `foo.bar'.
2004 else if (c == '/' || c == '.')
2005 buf[(*here)++] = '_';
2006 else if ((c >= '0' && c <= '9')
2007 || (c >= 'a' && c <= 'z')
2008 || (c >= 'A' && c <= 'Z'))
2009 buf[(*here)++] = (char) c;
2010 else
2012 // "Unicode" character.
2013 buf[(*here)++] = '_';
2014 buf[(*here)++] = '0';
2015 for (int i = 0; i < 4; ++i)
2017 int val = c & 0x0f;
2018 buf[(*here) + 3 - i] = (val > 10) ? ('a' + val - 10) : ('0' + val);
2019 c >>= 4;
2021 *here += 4;
2025 // Compute a mangled name for a native function. This computes the
2026 // long name, and also returns an index which indicates where a NUL
2027 // can be placed to create the short name. This function assumes that
2028 // the buffer is large enough for its results.
2029 static void
2030 mangled_name (jclass klass, _Jv_Utf8Const *func_name,
2031 _Jv_Utf8Const *signature, char *buf, int *long_start)
2033 strcpy (buf, "Java_");
2034 int here = 5;
2036 // Add fully qualified class name.
2037 jchar *chars = _Jv_GetStringChars (klass->getName ());
2038 jint len = klass->getName ()->length ();
2039 for (int i = 0; i < len; ++i)
2040 add_char (buf, chars[i], &here);
2042 // Don't use add_char because we need a literal `_'.
2043 buf[here++] = '_';
2045 const unsigned char *fn = (const unsigned char *) func_name->chars ();
2046 const unsigned char *limit = fn + func_name->len ();
2047 for (int i = 0; ; ++i)
2049 int ch = UTF8_GET (fn, limit);
2050 if (ch < 0)
2051 break;
2052 add_char (buf, ch, &here);
2055 // This is where the long signature begins.
2056 *long_start = here;
2057 buf[here++] = '_';
2058 buf[here++] = '_';
2060 const unsigned char *sig = (const unsigned char *) signature->chars ();
2061 limit = sig + signature->len ();
2062 JvAssert (sig[0] == '(');
2063 ++sig;
2064 while (1)
2066 int ch = UTF8_GET (sig, limit);
2067 if (ch == ')' || ch < 0)
2068 break;
2069 add_char (buf, ch, &here);
2072 buf[here] = '\0';
2075 // Return the current thread's JNIEnv; if one does not exist, create
2076 // it. Also create a new system frame for use. This is `extern "C"'
2077 // because the compiler calls it.
2078 extern "C" JNIEnv *
2079 _Jv_GetJNIEnvNewFrame (jclass klass)
2081 JNIEnv *env = _Jv_GetCurrentJNIEnv ();
2082 if (__builtin_expect (env == NULL, false))
2084 env = (JNIEnv *) _Jv_MallocUnchecked (sizeof (JNIEnv));
2085 env->p = &_Jv_JNIFunctions;
2086 env->klass = klass;
2087 env->locals = NULL;
2088 // We set env->ex below.
2090 // Set up the bottom, reusable frame.
2091 env->bottom_locals = (_Jv_JNI_LocalFrame *)
2092 _Jv_MallocUnchecked (sizeof (_Jv_JNI_LocalFrame)
2093 + (FRAME_SIZE
2094 * sizeof (jobject)));
2096 env->bottom_locals->marker = MARK_SYSTEM;
2097 env->bottom_locals->size = FRAME_SIZE;
2098 env->bottom_locals->next = NULL;
2099 env->bottom_locals->allocated_p = 0;
2100 memset (&env->bottom_locals->vec[0], 0,
2101 env->bottom_locals->size * sizeof (jobject));
2103 _Jv_SetCurrentJNIEnv (env);
2106 // If we're in a simple JNI call (non-nested), we can just reuse the
2107 // locals frame we allocated many calls ago, back when the env was first
2108 // built, above.
2110 if (__builtin_expect (env->locals == NULL, true))
2111 env->locals = env->bottom_locals;
2113 else
2115 // Alternatively, we might be re-entering JNI, in which case we can't
2116 // reuse the bottom_locals frame, because it is already underneath
2117 // us. So we need to make a new one.
2119 _Jv_JNI_LocalFrame *frame
2120 = (_Jv_JNI_LocalFrame *) _Jv_MallocUnchecked (sizeof (_Jv_JNI_LocalFrame)
2121 + (FRAME_SIZE
2122 * sizeof (jobject)));
2124 frame->marker = MARK_SYSTEM;
2125 frame->size = FRAME_SIZE;
2126 frame->allocated_p = 0;
2127 frame->next = env->locals;
2129 memset (&frame->vec[0], 0,
2130 frame->size * sizeof (jobject));
2132 env->locals = frame;
2135 env->ex = NULL;
2137 return env;
2140 // Destroy the env's reusable resources. This is called from the thread
2141 // destructor "finalize_native" in natThread.cc
2142 void
2143 _Jv_FreeJNIEnv (_Jv_JNIEnv *env)
2145 if (env == NULL)
2146 return;
2148 if (env->bottom_locals != NULL)
2149 _Jv_Free (env->bottom_locals);
2151 _Jv_Free (env);
2154 // Return the function which implements a particular JNI method. If
2155 // we can't find the function, we throw the appropriate exception.
2156 // This is `extern "C"' because the compiler uses it.
2157 extern "C" void *
2158 _Jv_LookupJNIMethod (jclass klass, _Jv_Utf8Const *name,
2159 _Jv_Utf8Const *signature, MAYBE_UNUSED int args_size)
2161 int name_length = name->len();
2162 int sig_length = signature->len();
2163 char buf[10 + 6 * (name_length + sig_length) + 12];
2164 int long_start;
2165 void *function;
2167 // Synchronize on something convenient. Right now we use the hash.
2168 JvSynchronize sync (global_ref_table);
2170 // First see if we have an override in the hash table.
2171 strncpy (buf, name->chars (), name_length);
2172 buf[name_length] = '\0';
2173 strncpy (buf + name_length + 1, signature->chars (), sig_length);
2174 buf[name_length + sig_length + 1] = '\0';
2175 JNINativeMethod meth;
2176 meth.name = buf;
2177 meth.signature = buf + name_length + 1;
2178 function = nathash_find (&meth);
2179 if (function != NULL)
2180 return function;
2182 // If there was no override, then look in the symbol table.
2183 buf[0] = '_';
2184 mangled_name (klass, name, signature, buf + 1, &long_start);
2185 char c = buf[long_start + 1];
2186 buf[long_start + 1] = '\0';
2188 function = _Jv_FindSymbolInExecutable (buf + 1);
2189 #ifdef WIN32
2190 // On Win32, we use the "stdcall" calling convention (see JNICALL
2191 // in jni.h).
2193 // For a function named 'fooBar' that takes 'nn' bytes as arguments,
2194 // by default, MinGW GCC exports it as 'fooBar@nn', MSVC exports it
2195 // as '_fooBar@nn' and Borland C exports it as 'fooBar'. We try to
2196 // take care of all these variations here.
2198 char asz_buf[12]; /* '@' + '2147483647' (32-bit INT_MAX) + '\0' */
2199 char long_nm_sv[11]; /* Ditto, except for the '\0'. */
2201 if (function == NULL)
2203 // We have tried searching for the 'fooBar' form (BCC) - now
2204 // try the others.
2206 // First, save the part of the long name that will be damaged
2207 // by appending '@nn'.
2208 memcpy (long_nm_sv, (buf + long_start + 1 + 1), sizeof (long_nm_sv));
2210 sprintf (asz_buf, "@%d", args_size);
2211 strcat (buf, asz_buf);
2213 // Search for the '_fooBar@nn' form (MSVC).
2214 function = _Jv_FindSymbolInExecutable (buf);
2216 if (function == NULL)
2218 // Search for the 'fooBar@nn' form (MinGW GCC).
2219 function = _Jv_FindSymbolInExecutable (buf + 1);
2222 #endif /* WIN32 */
2224 if (function == NULL)
2226 buf[long_start + 1] = c;
2227 #ifdef WIN32
2228 // Restore the part of the long name that was damaged by
2229 // appending the '@nn'.
2230 memcpy ((buf + long_start + 1 + 1), long_nm_sv, sizeof (long_nm_sv));
2231 #endif /* WIN32 */
2232 function = _Jv_FindSymbolInExecutable (buf + 1);
2233 if (function == NULL)
2235 #ifdef WIN32
2236 strcat (buf, asz_buf);
2237 function = _Jv_FindSymbolInExecutable (buf);
2238 if (function == NULL)
2239 function = _Jv_FindSymbolInExecutable (buf + 1);
2241 if (function == NULL)
2242 #endif /* WIN32 */
2244 jstring str = JvNewStringUTF (name->chars ());
2245 throw new java::lang::UnsatisfiedLinkError (str);
2250 return function;
2253 #ifdef INTERPRETER
2255 // This function is the stub which is used to turn an ordinary (CNI)
2256 // method call into a JNI call.
2257 void
2258 _Jv_JNIMethod::call (ffi_cif *, void *ret, ffi_raw *args, void *__this)
2260 _Jv_JNIMethod* _this = (_Jv_JNIMethod *) __this;
2262 JNIEnv *env = _Jv_GetJNIEnvNewFrame (_this->defining_class);
2264 // FIXME: we should mark every reference parameter as a local. For
2265 // now we assume a conservative GC, and we assume that the
2266 // references are on the stack somewhere.
2268 // We cache the value that we find, of course, but if we don't find
2269 // a value we don't cache that fact -- we might subsequently load a
2270 // library which finds the function in question.
2272 // Synchronize on a convenient object to ensure sanity in case two
2273 // threads reach this point for the same function at the same
2274 // time.
2275 JvSynchronize sync (global_ref_table);
2276 if (_this->function == NULL)
2278 int args_size = sizeof (JNIEnv *) + _this->args_raw_size;
2280 if (_this->self->accflags & java::lang::reflect::Modifier::STATIC)
2281 args_size += sizeof (_this->defining_class);
2283 _this->function = _Jv_LookupJNIMethod (_this->defining_class,
2284 _this->self->name,
2285 _this->self->signature,
2286 args_size);
2290 JvAssert (_this->args_raw_size % sizeof (ffi_raw) == 0);
2291 ffi_raw real_args[2 + _this->args_raw_size / sizeof (ffi_raw)];
2292 int offset = 0;
2294 // First argument is always the environment pointer.
2295 real_args[offset++].ptr = env;
2297 // For a static method, we pass in the Class. For non-static
2298 // methods, the `this' argument is already handled.
2299 if ((_this->self->accflags & java::lang::reflect::Modifier::STATIC))
2300 real_args[offset++].ptr = _this->defining_class;
2302 // In libgcj, the callee synchronizes.
2303 jobject sync = NULL;
2304 if ((_this->self->accflags & java::lang::reflect::Modifier::SYNCHRONIZED))
2306 if ((_this->self->accflags & java::lang::reflect::Modifier::STATIC))
2307 sync = _this->defining_class;
2308 else
2309 sync = (jobject) args[0].ptr;
2310 _Jv_MonitorEnter (sync);
2313 // Copy over passed-in arguments.
2314 memcpy (&real_args[offset], args, _this->args_raw_size);
2316 // The actual call to the JNI function.
2317 #if FFI_NATIVE_RAW_API
2318 ffi_raw_call (&_this->jni_cif, (void (*)()) _this->function,
2319 ret, real_args);
2320 #else
2321 ffi_java_raw_call (&_this->jni_cif, (void (*)()) _this->function,
2322 ret, real_args);
2323 #endif
2325 // We might need to unwrap a JNI weak reference here.
2326 if (_this->jni_cif.rtype == &ffi_type_pointer)
2328 _Jv_value *val = (_Jv_value *) ret;
2329 val->object_value = unwrap (val->object_value);
2332 if (sync != NULL)
2333 _Jv_MonitorExit (sync);
2335 _Jv_JNI_PopSystemFrame (env);
2338 #endif /* INTERPRETER */
2343 // Invocation API.
2346 // An internal helper function.
2347 static jint
2348 _Jv_JNI_AttachCurrentThread (JavaVM *, jstring name, void **penv,
2349 void *args, jboolean is_daemon)
2351 JavaVMAttachArgs *attach = reinterpret_cast<JavaVMAttachArgs *> (args);
2352 java::lang::ThreadGroup *group = NULL;
2354 if (attach)
2356 // FIXME: do we really want to support 1.1?
2357 if (attach->version != JNI_VERSION_1_4
2358 && attach->version != JNI_VERSION_1_2
2359 && attach->version != JNI_VERSION_1_1)
2360 return JNI_EVERSION;
2362 JvAssert (java::lang::ThreadGroup::class$.isInstance (attach->group));
2363 group = reinterpret_cast<java::lang::ThreadGroup *> (attach->group);
2366 // Attaching an already-attached thread is a no-op.
2367 JNIEnv *env = _Jv_GetCurrentJNIEnv ();
2368 if (env != NULL)
2370 *penv = reinterpret_cast<void *> (env);
2371 return 0;
2374 env = (JNIEnv *) _Jv_MallocUnchecked (sizeof (JNIEnv));
2375 if (env == NULL)
2376 return JNI_ERR;
2377 env->p = &_Jv_JNIFunctions;
2378 env->ex = NULL;
2379 env->klass = NULL;
2380 env->bottom_locals
2381 = (_Jv_JNI_LocalFrame *) _Jv_MallocUnchecked (sizeof (_Jv_JNI_LocalFrame)
2382 + (FRAME_SIZE
2383 * sizeof (jobject)));
2384 env->locals = env->bottom_locals;
2385 if (env->locals == NULL)
2387 _Jv_Free (env);
2388 return JNI_ERR;
2391 env->locals->allocated_p = 0;
2392 env->locals->marker = MARK_SYSTEM;
2393 env->locals->size = FRAME_SIZE;
2394 env->locals->next = NULL;
2396 for (int i = 0; i < env->locals->size; ++i)
2397 env->locals->vec[i] = NULL;
2399 *penv = reinterpret_cast<void *> (env);
2401 // This thread might already be a Java thread -- this function might
2402 // have been called simply to set the new JNIEnv.
2403 if (_Jv_ThreadCurrent () == NULL)
2407 if (is_daemon)
2408 _Jv_AttachCurrentThreadAsDaemon (name, group);
2409 else
2410 _Jv_AttachCurrentThread (name, group);
2412 catch (jthrowable t)
2414 return JNI_ERR;
2417 _Jv_SetCurrentJNIEnv (env);
2419 return 0;
2422 // This is the one actually used by JNI.
2423 jint JNICALL
2424 _Jv_JNI_AttachCurrentThread (JavaVM *vm, void **penv, void *args)
2426 return _Jv_JNI_AttachCurrentThread (vm, NULL, penv, args, false);
2429 static jint JNICALL
2430 _Jv_JNI_AttachCurrentThreadAsDaemon (JavaVM *vm, void **penv,
2431 void *args)
2433 return _Jv_JNI_AttachCurrentThread (vm, NULL, penv, args, true);
2436 static jint JNICALL
2437 _Jv_JNI_DestroyJavaVM (JavaVM *vm)
2439 JvAssert (_Jv_the_vm && vm == _Jv_the_vm);
2441 union
2443 JNIEnv *env;
2444 void *env_p;
2447 if (_Jv_ThreadCurrent () != NULL)
2449 jstring main_name;
2450 // This sucks.
2453 main_name = JvNewStringLatin1 ("main");
2455 catch (jthrowable t)
2457 return JNI_ERR;
2460 jint r = _Jv_JNI_AttachCurrentThread (vm, main_name, &env_p,
2461 NULL, false);
2462 if (r < 0)
2463 return r;
2465 else
2466 env = _Jv_GetCurrentJNIEnv ();
2468 _Jv_ThreadWait ();
2470 // Docs say that this always returns an error code.
2471 return JNI_ERR;
2474 jint JNICALL
2475 _Jv_JNI_DetachCurrentThread (JavaVM *)
2477 jint code = _Jv_DetachCurrentThread ();
2478 return code ? JNI_EDETACHED : 0;
2481 static jint JNICALL
2482 _Jv_JNI_GetEnv (JavaVM *, void **penv, jint version)
2484 if (_Jv_ThreadCurrent () == NULL)
2486 *penv = NULL;
2487 return JNI_EDETACHED;
2490 #ifdef ENABLE_JVMPI
2491 // Handle JVMPI requests.
2492 if (version == JVMPI_VERSION_1)
2494 *penv = (void *) &_Jv_JVMPI_Interface;
2495 return 0;
2497 #endif
2499 // Handle JVMTI requests
2500 if (version == JVMTI_VERSION_1_0)
2502 *penv = (void *) _Jv_GetJVMTIEnv ();
2503 return 0;
2506 // FIXME: do we really want to support 1.1?
2507 if (version != JNI_VERSION_1_4 && version != JNI_VERSION_1_2
2508 && version != JNI_VERSION_1_1)
2510 *penv = NULL;
2511 return JNI_EVERSION;
2514 *penv = (void *) _Jv_GetCurrentJNIEnv ();
2515 return 0;
2518 JavaVM *
2519 _Jv_GetJavaVM ()
2521 // FIXME: synchronize
2522 if (! _Jv_the_vm)
2524 JavaVM *nvm = (JavaVM *) _Jv_MallocUnchecked (sizeof (JavaVM));
2525 if (nvm != NULL)
2526 nvm->functions = &_Jv_JNI_InvokeFunctions;
2527 _Jv_the_vm = nvm;
2530 // If this is a Java thread, we want to make sure it has an
2531 // associated JNIEnv.
2532 if (_Jv_ThreadCurrent () != NULL)
2534 void *ignore;
2535 _Jv_JNI_AttachCurrentThread (_Jv_the_vm, &ignore, NULL);
2538 return _Jv_the_vm;
2541 static jint JNICALL
2542 _Jv_JNI_GetJavaVM (JNIEnv *, JavaVM **vm)
2544 *vm = _Jv_GetJavaVM ();
2545 return *vm == NULL ? JNI_ERR : JNI_OK;
2550 #define RESERVED NULL
2552 struct JNINativeInterface _Jv_JNIFunctions =
2554 RESERVED,
2555 RESERVED,
2556 RESERVED,
2557 RESERVED,
2558 _Jv_JNI_GetVersion, // GetVersion
2559 _Jv_JNI_DefineClass, // DefineClass
2560 _Jv_JNI_FindClass, // FindClass
2561 _Jv_JNI_FromReflectedMethod, // FromReflectedMethod
2562 _Jv_JNI_FromReflectedField, // FromReflectedField
2563 _Jv_JNI_ToReflectedMethod, // ToReflectedMethod
2564 _Jv_JNI_GetSuperclass, // GetSuperclass
2565 _Jv_JNI_IsAssignableFrom, // IsAssignableFrom
2566 _Jv_JNI_ToReflectedField, // ToReflectedField
2567 _Jv_JNI_Throw, // Throw
2568 _Jv_JNI_ThrowNew, // ThrowNew
2569 _Jv_JNI_ExceptionOccurred, // ExceptionOccurred
2570 _Jv_JNI_ExceptionDescribe, // ExceptionDescribe
2571 _Jv_JNI_ExceptionClear, // ExceptionClear
2572 _Jv_JNI_FatalError, // FatalError
2574 _Jv_JNI_PushLocalFrame, // PushLocalFrame
2575 _Jv_JNI_PopLocalFrame, // PopLocalFrame
2576 _Jv_JNI_NewGlobalRef, // NewGlobalRef
2577 _Jv_JNI_DeleteGlobalRef, // DeleteGlobalRef
2578 _Jv_JNI_DeleteLocalRef, // DeleteLocalRef
2580 _Jv_JNI_IsSameObject, // IsSameObject
2582 _Jv_JNI_NewLocalRef, // NewLocalRef
2583 _Jv_JNI_EnsureLocalCapacity, // EnsureLocalCapacity
2585 _Jv_JNI_AllocObject, // AllocObject
2586 _Jv_JNI_NewObject, // NewObject
2587 _Jv_JNI_NewObjectV, // NewObjectV
2588 _Jv_JNI_NewObjectA, // NewObjectA
2589 _Jv_JNI_GetObjectClass, // GetObjectClass
2590 _Jv_JNI_IsInstanceOf, // IsInstanceOf
2591 _Jv_JNI_GetAnyMethodID<false>, // GetMethodID
2593 _Jv_JNI_CallMethod<jobject>, // CallObjectMethod
2594 _Jv_JNI_CallMethodV<jobject>, // CallObjectMethodV
2595 _Jv_JNI_CallMethodA<jobject>, // CallObjectMethodA
2596 _Jv_JNI_CallMethod<jboolean>, // CallBooleanMethod
2597 _Jv_JNI_CallMethodV<jboolean>, // CallBooleanMethodV
2598 _Jv_JNI_CallMethodA<jboolean>, // CallBooleanMethodA
2599 _Jv_JNI_CallMethod<jbyte>, // CallByteMethod
2600 _Jv_JNI_CallMethodV<jbyte>, // CallByteMethodV
2601 _Jv_JNI_CallMethodA<jbyte>, // CallByteMethodA
2602 _Jv_JNI_CallMethod<jchar>, // CallCharMethod
2603 _Jv_JNI_CallMethodV<jchar>, // CallCharMethodV
2604 _Jv_JNI_CallMethodA<jchar>, // CallCharMethodA
2605 _Jv_JNI_CallMethod<jshort>, // CallShortMethod
2606 _Jv_JNI_CallMethodV<jshort>, // CallShortMethodV
2607 _Jv_JNI_CallMethodA<jshort>, // CallShortMethodA
2608 _Jv_JNI_CallMethod<jint>, // CallIntMethod
2609 _Jv_JNI_CallMethodV<jint>, // CallIntMethodV
2610 _Jv_JNI_CallMethodA<jint>, // CallIntMethodA
2611 _Jv_JNI_CallMethod<jlong>, // CallLongMethod
2612 _Jv_JNI_CallMethodV<jlong>, // CallLongMethodV
2613 _Jv_JNI_CallMethodA<jlong>, // CallLongMethodA
2614 _Jv_JNI_CallMethod<jfloat>, // CallFloatMethod
2615 _Jv_JNI_CallMethodV<jfloat>, // CallFloatMethodV
2616 _Jv_JNI_CallMethodA<jfloat>, // CallFloatMethodA
2617 _Jv_JNI_CallMethod<jdouble>, // CallDoubleMethod
2618 _Jv_JNI_CallMethodV<jdouble>, // CallDoubleMethodV
2619 _Jv_JNI_CallMethodA<jdouble>, // CallDoubleMethodA
2620 _Jv_JNI_CallVoidMethod, // CallVoidMethod
2621 _Jv_JNI_CallVoidMethodV, // CallVoidMethodV
2622 _Jv_JNI_CallVoidMethodA, // CallVoidMethodA
2624 // Nonvirtual method invocation functions follow.
2625 _Jv_JNI_CallAnyMethod<jobject, nonvirtual>, // CallNonvirtualObjectMethod
2626 _Jv_JNI_CallAnyMethodV<jobject, nonvirtual>, // CallNonvirtualObjectMethodV
2627 _Jv_JNI_CallAnyMethodA<jobject, nonvirtual>, // CallNonvirtualObjectMethodA
2628 _Jv_JNI_CallAnyMethod<jboolean, nonvirtual>, // CallNonvirtualBooleanMethod
2629 _Jv_JNI_CallAnyMethodV<jboolean, nonvirtual>, // CallNonvirtualBooleanMethodV
2630 _Jv_JNI_CallAnyMethodA<jboolean, nonvirtual>, // CallNonvirtualBooleanMethodA
2631 _Jv_JNI_CallAnyMethod<jbyte, nonvirtual>, // CallNonvirtualByteMethod
2632 _Jv_JNI_CallAnyMethodV<jbyte, nonvirtual>, // CallNonvirtualByteMethodV
2633 _Jv_JNI_CallAnyMethodA<jbyte, nonvirtual>, // CallNonvirtualByteMethodA
2634 _Jv_JNI_CallAnyMethod<jchar, nonvirtual>, // CallNonvirtualCharMethod
2635 _Jv_JNI_CallAnyMethodV<jchar, nonvirtual>, // CallNonvirtualCharMethodV
2636 _Jv_JNI_CallAnyMethodA<jchar, nonvirtual>, // CallNonvirtualCharMethodA
2637 _Jv_JNI_CallAnyMethod<jshort, nonvirtual>, // CallNonvirtualShortMethod
2638 _Jv_JNI_CallAnyMethodV<jshort, nonvirtual>, // CallNonvirtualShortMethodV
2639 _Jv_JNI_CallAnyMethodA<jshort, nonvirtual>, // CallNonvirtualShortMethodA
2640 _Jv_JNI_CallAnyMethod<jint, nonvirtual>, // CallNonvirtualIntMethod
2641 _Jv_JNI_CallAnyMethodV<jint, nonvirtual>, // CallNonvirtualIntMethodV
2642 _Jv_JNI_CallAnyMethodA<jint, nonvirtual>, // CallNonvirtualIntMethodA
2643 _Jv_JNI_CallAnyMethod<jlong, nonvirtual>, // CallNonvirtualLongMethod
2644 _Jv_JNI_CallAnyMethodV<jlong, nonvirtual>, // CallNonvirtualLongMethodV
2645 _Jv_JNI_CallAnyMethodA<jlong, nonvirtual>, // CallNonvirtualLongMethodA
2646 _Jv_JNI_CallAnyMethod<jfloat, nonvirtual>, // CallNonvirtualFloatMethod
2647 _Jv_JNI_CallAnyMethodV<jfloat, nonvirtual>, // CallNonvirtualFloatMethodV
2648 _Jv_JNI_CallAnyMethodA<jfloat, nonvirtual>, // CallNonvirtualFloatMethodA
2649 _Jv_JNI_CallAnyMethod<jdouble, nonvirtual>, // CallNonvirtualDoubleMethod
2650 _Jv_JNI_CallAnyMethodV<jdouble, nonvirtual>, // CallNonvirtualDoubleMethodV
2651 _Jv_JNI_CallAnyMethodA<jdouble, nonvirtual>, // CallNonvirtualDoubleMethodA
2652 _Jv_JNI_CallAnyVoidMethod<nonvirtual>, // CallNonvirtualVoidMethod
2653 _Jv_JNI_CallAnyVoidMethodV<nonvirtual>, // CallNonvirtualVoidMethodV
2654 _Jv_JNI_CallAnyVoidMethodA<nonvirtual>, // CallNonvirtualVoidMethodA
2656 _Jv_JNI_GetAnyFieldID<false>, // GetFieldID
2657 _Jv_JNI_GetField<jobject>, // GetObjectField
2658 _Jv_JNI_GetField<jboolean>, // GetBooleanField
2659 _Jv_JNI_GetField<jbyte>, // GetByteField
2660 _Jv_JNI_GetField<jchar>, // GetCharField
2661 _Jv_JNI_GetField<jshort>, // GetShortField
2662 _Jv_JNI_GetField<jint>, // GetIntField
2663 _Jv_JNI_GetField<jlong>, // GetLongField
2664 _Jv_JNI_GetField<jfloat>, // GetFloatField
2665 _Jv_JNI_GetField<jdouble>, // GetDoubleField
2666 _Jv_JNI_SetField, // SetObjectField
2667 _Jv_JNI_SetField, // SetBooleanField
2668 _Jv_JNI_SetField, // SetByteField
2669 _Jv_JNI_SetField, // SetCharField
2670 _Jv_JNI_SetField, // SetShortField
2671 _Jv_JNI_SetField, // SetIntField
2672 _Jv_JNI_SetField, // SetLongField
2673 _Jv_JNI_SetField, // SetFloatField
2674 _Jv_JNI_SetField, // SetDoubleField
2675 _Jv_JNI_GetAnyMethodID<true>, // GetStaticMethodID
2677 _Jv_JNI_CallStaticMethod<jobject>, // CallStaticObjectMethod
2678 _Jv_JNI_CallStaticMethodV<jobject>, // CallStaticObjectMethodV
2679 _Jv_JNI_CallStaticMethodA<jobject>, // CallStaticObjectMethodA
2680 _Jv_JNI_CallStaticMethod<jboolean>, // CallStaticBooleanMethod
2681 _Jv_JNI_CallStaticMethodV<jboolean>, // CallStaticBooleanMethodV
2682 _Jv_JNI_CallStaticMethodA<jboolean>, // CallStaticBooleanMethodA
2683 _Jv_JNI_CallStaticMethod<jbyte>, // CallStaticByteMethod
2684 _Jv_JNI_CallStaticMethodV<jbyte>, // CallStaticByteMethodV
2685 _Jv_JNI_CallStaticMethodA<jbyte>, // CallStaticByteMethodA
2686 _Jv_JNI_CallStaticMethod<jchar>, // CallStaticCharMethod
2687 _Jv_JNI_CallStaticMethodV<jchar>, // CallStaticCharMethodV
2688 _Jv_JNI_CallStaticMethodA<jchar>, // CallStaticCharMethodA
2689 _Jv_JNI_CallStaticMethod<jshort>, // CallStaticShortMethod
2690 _Jv_JNI_CallStaticMethodV<jshort>, // CallStaticShortMethodV
2691 _Jv_JNI_CallStaticMethodA<jshort>, // CallStaticShortMethodA
2692 _Jv_JNI_CallStaticMethod<jint>, // CallStaticIntMethod
2693 _Jv_JNI_CallStaticMethodV<jint>, // CallStaticIntMethodV
2694 _Jv_JNI_CallStaticMethodA<jint>, // CallStaticIntMethodA
2695 _Jv_JNI_CallStaticMethod<jlong>, // CallStaticLongMethod
2696 _Jv_JNI_CallStaticMethodV<jlong>, // CallStaticLongMethodV
2697 _Jv_JNI_CallStaticMethodA<jlong>, // CallStaticLongMethodA
2698 _Jv_JNI_CallStaticMethod<jfloat>, // CallStaticFloatMethod
2699 _Jv_JNI_CallStaticMethodV<jfloat>, // CallStaticFloatMethodV
2700 _Jv_JNI_CallStaticMethodA<jfloat>, // CallStaticFloatMethodA
2701 _Jv_JNI_CallStaticMethod<jdouble>, // CallStaticDoubleMethod
2702 _Jv_JNI_CallStaticMethodV<jdouble>, // CallStaticDoubleMethodV
2703 _Jv_JNI_CallStaticMethodA<jdouble>, // CallStaticDoubleMethodA
2704 _Jv_JNI_CallStaticVoidMethod, // CallStaticVoidMethod
2705 _Jv_JNI_CallStaticVoidMethodV, // CallStaticVoidMethodV
2706 _Jv_JNI_CallStaticVoidMethodA, // CallStaticVoidMethodA
2708 _Jv_JNI_GetAnyFieldID<true>, // GetStaticFieldID
2709 _Jv_JNI_GetStaticField<jobject>, // GetStaticObjectField
2710 _Jv_JNI_GetStaticField<jboolean>, // GetStaticBooleanField
2711 _Jv_JNI_GetStaticField<jbyte>, // GetStaticByteField
2712 _Jv_JNI_GetStaticField<jchar>, // GetStaticCharField
2713 _Jv_JNI_GetStaticField<jshort>, // GetStaticShortField
2714 _Jv_JNI_GetStaticField<jint>, // GetStaticIntField
2715 _Jv_JNI_GetStaticField<jlong>, // GetStaticLongField
2716 _Jv_JNI_GetStaticField<jfloat>, // GetStaticFloatField
2717 _Jv_JNI_GetStaticField<jdouble>, // GetStaticDoubleField
2718 _Jv_JNI_SetStaticField, // SetStaticObjectField
2719 _Jv_JNI_SetStaticField, // SetStaticBooleanField
2720 _Jv_JNI_SetStaticField, // SetStaticByteField
2721 _Jv_JNI_SetStaticField, // SetStaticCharField
2722 _Jv_JNI_SetStaticField, // SetStaticShortField
2723 _Jv_JNI_SetStaticField, // SetStaticIntField
2724 _Jv_JNI_SetStaticField, // SetStaticLongField
2725 _Jv_JNI_SetStaticField, // SetStaticFloatField
2726 _Jv_JNI_SetStaticField, // SetStaticDoubleField
2727 _Jv_JNI_NewString, // NewString
2728 _Jv_JNI_GetStringLength, // GetStringLength
2729 _Jv_JNI_GetStringChars, // GetStringChars
2730 _Jv_JNI_ReleaseStringChars, // ReleaseStringChars
2731 _Jv_JNI_NewStringUTF, // NewStringUTF
2732 _Jv_JNI_GetStringUTFLength, // GetStringUTFLength
2733 _Jv_JNI_GetStringUTFChars, // GetStringUTFChars
2734 _Jv_JNI_ReleaseStringUTFChars, // ReleaseStringUTFChars
2735 _Jv_JNI_GetArrayLength, // GetArrayLength
2736 _Jv_JNI_NewObjectArray, // NewObjectArray
2737 _Jv_JNI_GetObjectArrayElement, // GetObjectArrayElement
2738 _Jv_JNI_SetObjectArrayElement, // SetObjectArrayElement
2739 _Jv_JNI_NewPrimitiveArray<jboolean, JvPrimClass (boolean)>,
2740 // NewBooleanArray
2741 _Jv_JNI_NewPrimitiveArray<jbyte, JvPrimClass (byte)>, // NewByteArray
2742 _Jv_JNI_NewPrimitiveArray<jchar, JvPrimClass (char)>, // NewCharArray
2743 _Jv_JNI_NewPrimitiveArray<jshort, JvPrimClass (short)>, // NewShortArray
2744 _Jv_JNI_NewPrimitiveArray<jint, JvPrimClass (int)>, // NewIntArray
2745 _Jv_JNI_NewPrimitiveArray<jlong, JvPrimClass (long)>, // NewLongArray
2746 _Jv_JNI_NewPrimitiveArray<jfloat, JvPrimClass (float)>, // NewFloatArray
2747 _Jv_JNI_NewPrimitiveArray<jdouble, JvPrimClass (double)>, // NewDoubleArray
2748 _Jv_JNI_GetPrimitiveArrayElements<jboolean, JvPrimClass (boolean)>,
2749 // GetBooleanArrayElements
2750 _Jv_JNI_GetPrimitiveArrayElements<jbyte, JvPrimClass (byte)>,
2751 // GetByteArrayElements
2752 _Jv_JNI_GetPrimitiveArrayElements<jchar, JvPrimClass (char)>,
2753 // GetCharArrayElements
2754 _Jv_JNI_GetPrimitiveArrayElements<jshort, JvPrimClass (short)>,
2755 // GetShortArrayElements
2756 _Jv_JNI_GetPrimitiveArrayElements<jint, JvPrimClass (int)>,
2757 // GetIntArrayElements
2758 _Jv_JNI_GetPrimitiveArrayElements<jlong, JvPrimClass (long)>,
2759 // GetLongArrayElements
2760 _Jv_JNI_GetPrimitiveArrayElements<jfloat, JvPrimClass (float)>,
2761 // GetFloatArrayElements
2762 _Jv_JNI_GetPrimitiveArrayElements<jdouble, JvPrimClass (double)>,
2763 // GetDoubleArrayElements
2764 _Jv_JNI_ReleasePrimitiveArrayElements<jboolean, JvPrimClass (boolean)>,
2765 // ReleaseBooleanArrayElements
2766 _Jv_JNI_ReleasePrimitiveArrayElements<jbyte, JvPrimClass (byte)>,
2767 // ReleaseByteArrayElements
2768 _Jv_JNI_ReleasePrimitiveArrayElements<jchar, JvPrimClass (char)>,
2769 // ReleaseCharArrayElements
2770 _Jv_JNI_ReleasePrimitiveArrayElements<jshort, JvPrimClass (short)>,
2771 // ReleaseShortArrayElements
2772 _Jv_JNI_ReleasePrimitiveArrayElements<jint, JvPrimClass (int)>,
2773 // ReleaseIntArrayElements
2774 _Jv_JNI_ReleasePrimitiveArrayElements<jlong, JvPrimClass (long)>,
2775 // ReleaseLongArrayElements
2776 _Jv_JNI_ReleasePrimitiveArrayElements<jfloat, JvPrimClass (float)>,
2777 // ReleaseFloatArrayElements
2778 _Jv_JNI_ReleasePrimitiveArrayElements<jdouble, JvPrimClass (double)>,
2779 // ReleaseDoubleArrayElements
2780 _Jv_JNI_GetPrimitiveArrayRegion<jboolean, JvPrimClass (boolean)>,
2781 // GetBooleanArrayRegion
2782 _Jv_JNI_GetPrimitiveArrayRegion<jbyte, JvPrimClass (byte)>,
2783 // GetByteArrayRegion
2784 _Jv_JNI_GetPrimitiveArrayRegion<jchar, JvPrimClass (char)>,
2785 // GetCharArrayRegion
2786 _Jv_JNI_GetPrimitiveArrayRegion<jshort, JvPrimClass (short)>,
2787 // GetShortArrayRegion
2788 _Jv_JNI_GetPrimitiveArrayRegion<jint, JvPrimClass (int)>,
2789 // GetIntArrayRegion
2790 _Jv_JNI_GetPrimitiveArrayRegion<jlong, JvPrimClass (long)>,
2791 // GetLongArrayRegion
2792 _Jv_JNI_GetPrimitiveArrayRegion<jfloat, JvPrimClass (float)>,
2793 // GetFloatArrayRegion
2794 _Jv_JNI_GetPrimitiveArrayRegion<jdouble, JvPrimClass (double)>,
2795 // GetDoubleArrayRegion
2796 _Jv_JNI_SetPrimitiveArrayRegion<jboolean, JvPrimClass (boolean)>,
2797 // SetBooleanArrayRegion
2798 _Jv_JNI_SetPrimitiveArrayRegion<jbyte, JvPrimClass (byte)>,
2799 // SetByteArrayRegion
2800 _Jv_JNI_SetPrimitiveArrayRegion<jchar, JvPrimClass (char)>,
2801 // SetCharArrayRegion
2802 _Jv_JNI_SetPrimitiveArrayRegion<jshort, JvPrimClass (short)>,
2803 // SetShortArrayRegion
2804 _Jv_JNI_SetPrimitiveArrayRegion<jint, JvPrimClass (int)>,
2805 // SetIntArrayRegion
2806 _Jv_JNI_SetPrimitiveArrayRegion<jlong, JvPrimClass (long)>,
2807 // SetLongArrayRegion
2808 _Jv_JNI_SetPrimitiveArrayRegion<jfloat, JvPrimClass (float)>,
2809 // SetFloatArrayRegion
2810 _Jv_JNI_SetPrimitiveArrayRegion<jdouble, JvPrimClass (double)>,
2811 // SetDoubleArrayRegion
2812 _Jv_JNI_RegisterNatives, // RegisterNatives
2813 _Jv_JNI_UnregisterNatives, // UnregisterNatives
2814 _Jv_JNI_MonitorEnter, // MonitorEnter
2815 _Jv_JNI_MonitorExit, // MonitorExit
2816 _Jv_JNI_GetJavaVM, // GetJavaVM
2818 _Jv_JNI_GetStringRegion, // GetStringRegion
2819 _Jv_JNI_GetStringUTFRegion, // GetStringUTFRegion
2820 _Jv_JNI_GetPrimitiveArrayCritical, // GetPrimitiveArrayCritical
2821 _Jv_JNI_ReleasePrimitiveArrayCritical, // ReleasePrimitiveArrayCritical
2822 _Jv_JNI_GetStringCritical, // GetStringCritical
2823 _Jv_JNI_ReleaseStringCritical, // ReleaseStringCritical
2825 _Jv_JNI_NewWeakGlobalRef, // NewWeakGlobalRef
2826 _Jv_JNI_DeleteWeakGlobalRef, // DeleteWeakGlobalRef
2828 _Jv_JNI_ExceptionCheck, // ExceptionCheck
2830 _Jv_JNI_NewDirectByteBuffer, // NewDirectByteBuffer
2831 _Jv_JNI_GetDirectBufferAddress, // GetDirectBufferAddress
2832 _Jv_JNI_GetDirectBufferCapacity // GetDirectBufferCapacity
2835 struct JNIInvokeInterface _Jv_JNI_InvokeFunctions =
2837 RESERVED,
2838 RESERVED,
2839 RESERVED,
2841 _Jv_JNI_DestroyJavaVM,
2842 _Jv_JNI_AttachCurrentThread,
2843 _Jv_JNI_DetachCurrentThread,
2844 _Jv_JNI_GetEnv,
2845 _Jv_JNI_AttachCurrentThreadAsDaemon