* config/rs6000/rs6000.c (rs6000_return_in_memory): Allow Altivec
[official-gcc.git] / libjava / jni.cc
blob6bfc4812d96eabbdea0a72a8150a34a4776c47c9
1 // jni.cc - JNI implementation, including the jump table.
3 /* Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004
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
26 #include <java/lang/Class.h>
27 #include <java/lang/ClassLoader.h>
28 #include <java/lang/Throwable.h>
29 #include <java/lang/ArrayIndexOutOfBoundsException.h>
30 #include <java/lang/StringIndexOutOfBoundsException.h>
31 #include <java/lang/StringBuffer.h>
32 #include <java/lang/UnsatisfiedLinkError.h>
33 #include <java/lang/InstantiationException.h>
34 #include <java/lang/NoSuchFieldError.h>
35 #include <java/lang/NoSuchMethodError.h>
36 #include <java/lang/reflect/Constructor.h>
37 #include <java/lang/reflect/Method.h>
38 #include <java/lang/reflect/Modifier.h>
39 #include <java/lang/OutOfMemoryError.h>
40 #include <java/lang/Integer.h>
41 #include <java/lang/ThreadGroup.h>
42 #include <java/lang/Thread.h>
43 #include <java/lang/IllegalAccessError.h>
44 #include <java/nio/DirectByteBufferImpl.h>
45 #include <java/nio/DirectByteBufferImpl$ReadWrite.h>
46 #include <java/util/IdentityHashMap.h>
47 #include <gnu/gcj/RawData.h>
49 #include <gcj/method.h>
50 #include <gcj/field.h>
52 #include <java-interp.h>
53 #include <java-threads.h>
55 using namespace gcj;
57 // This enum is used to select different template instantiations in
58 // the invocation code.
59 enum invocation_type
61 normal,
62 nonvirtual,
63 static_type,
64 constructor
67 // Forward declarations.
68 extern struct JNINativeInterface _Jv_JNIFunctions;
69 extern struct JNIInvokeInterface _Jv_JNI_InvokeFunctions;
71 // Number of slots in the default frame. The VM must allow at least
72 // 16.
73 #define FRAME_SIZE 32
75 // Mark value indicating this is an overflow frame.
76 #define MARK_NONE 0
77 // Mark value indicating this is a user frame.
78 #define MARK_USER 1
79 // Mark value indicating this is a system frame.
80 #define MARK_SYSTEM 2
82 // This structure is used to keep track of local references.
83 struct _Jv_JNI_LocalFrame
85 // This is true if this frame object represents a pushed frame (eg
86 // from PushLocalFrame).
87 int marker : 2;
89 // Number of elements in frame.
90 int size : 30;
92 // Next frame in chain.
93 _Jv_JNI_LocalFrame *next;
95 // The elements. These are allocated using the C "struct hack".
96 jobject vec[0];
99 // This holds a reference count for all local references.
100 static java::util::IdentityHashMap *local_ref_table;
101 // This holds a reference count for all global references.
102 static java::util::IdentityHashMap *global_ref_table;
104 // The only VM.
105 static JavaVM *the_vm;
107 #ifdef ENABLE_JVMPI
108 // The only JVMPI interface description.
109 static JVMPI_Interface _Jv_JVMPI_Interface;
111 static jint
112 jvmpiEnableEvent (jint event_type, void *)
114 switch (event_type)
116 case JVMPI_EVENT_OBJECT_ALLOC:
117 _Jv_JVMPI_Notify_OBJECT_ALLOC = _Jv_JVMPI_Interface.NotifyEvent;
118 break;
120 case JVMPI_EVENT_THREAD_START:
121 _Jv_JVMPI_Notify_THREAD_START = _Jv_JVMPI_Interface.NotifyEvent;
122 break;
124 case JVMPI_EVENT_THREAD_END:
125 _Jv_JVMPI_Notify_THREAD_END = _Jv_JVMPI_Interface.NotifyEvent;
126 break;
128 default:
129 return JVMPI_NOT_AVAILABLE;
132 return JVMPI_SUCCESS;
135 static jint
136 jvmpiDisableEvent (jint event_type, void *)
138 switch (event_type)
140 case JVMPI_EVENT_OBJECT_ALLOC:
141 _Jv_JVMPI_Notify_OBJECT_ALLOC = NULL;
142 break;
144 default:
145 return JVMPI_NOT_AVAILABLE;
148 return JVMPI_SUCCESS;
150 #endif
154 void
155 _Jv_JNI_Init (void)
157 local_ref_table = new java::util::IdentityHashMap;
158 global_ref_table = new java::util::IdentityHashMap;
160 #ifdef ENABLE_JVMPI
161 _Jv_JVMPI_Interface.version = 1;
162 _Jv_JVMPI_Interface.EnableEvent = &jvmpiEnableEvent;
163 _Jv_JVMPI_Interface.DisableEvent = &jvmpiDisableEvent;
164 _Jv_JVMPI_Interface.EnableGC = &_Jv_EnableGC;
165 _Jv_JVMPI_Interface.DisableGC = &_Jv_DisableGC;
166 _Jv_JVMPI_Interface.RunGC = &_Jv_RunGC;
167 #endif
170 // Tell the GC that a certain pointer is live.
171 static void
172 mark_for_gc (jobject obj, java::util::IdentityHashMap *ref_table)
174 JvSynchronize sync (ref_table);
176 using namespace java::lang;
177 Integer *refcount = (Integer *) ref_table->get (obj);
178 jint val = (refcount == NULL) ? 0 : refcount->intValue ();
179 // FIXME: what about out of memory error?
180 ref_table->put (obj, new Integer (val + 1));
183 // Unmark a pointer.
184 static void
185 unmark_for_gc (jobject obj, java::util::IdentityHashMap *ref_table)
187 JvSynchronize sync (ref_table);
189 using namespace java::lang;
190 Integer *refcount = (Integer *) ref_table->get (obj);
191 JvAssert (refcount);
192 jint val = refcount->intValue () - 1;
193 JvAssert (val >= 0);
194 if (val == 0)
195 ref_table->remove (obj);
196 else
197 // FIXME: what about out of memory error?
198 ref_table->put (obj, new Integer (val));
201 // "Unwrap" some random non-reference type. This exists to simplify
202 // other template functions.
203 template<typename T>
204 static T
205 unwrap (T val)
207 return val;
210 // Unwrap a weak reference, if required.
211 template<typename T>
212 static T *
213 unwrap (T *obj)
215 using namespace gnu::gcj::runtime;
216 // We can compare the class directly because JNIWeakRef is `final'.
217 // Doing it this way is much faster.
218 if (obj == NULL || obj->getClass () != &JNIWeakRef::class$)
219 return obj;
220 JNIWeakRef *wr = reinterpret_cast<JNIWeakRef *> (obj);
221 return reinterpret_cast<T *> (wr->get ());
226 static jobject JNICALL
227 _Jv_JNI_NewGlobalRef (JNIEnv *, jobject obj)
229 // This seems weird but I think it is correct.
230 obj = unwrap (obj);
231 mark_for_gc (obj, global_ref_table);
232 return obj;
235 static void JNICALL
236 _Jv_JNI_DeleteGlobalRef (JNIEnv *, jobject obj)
238 // This seems weird but I think it is correct.
239 obj = unwrap (obj);
240 unmark_for_gc (obj, global_ref_table);
243 static void JNICALL
244 _Jv_JNI_DeleteLocalRef (JNIEnv *env, jobject obj)
246 _Jv_JNI_LocalFrame *frame;
248 // This seems weird but I think it is correct.
249 obj = unwrap (obj);
251 for (frame = env->locals; frame != NULL; frame = frame->next)
253 for (int i = 0; i < frame->size; ++i)
255 if (frame->vec[i] == obj)
257 frame->vec[i] = NULL;
258 unmark_for_gc (obj, local_ref_table);
259 return;
263 // Don't go past a marked frame.
264 JvAssert (frame->marker == MARK_NONE);
267 JvAssert (0);
270 static jint JNICALL
271 _Jv_JNI_EnsureLocalCapacity (JNIEnv *env, jint size)
273 // It is easier to just always allocate a new frame of the requested
274 // size. This isn't the most efficient thing, but for now we don't
275 // care. Note that _Jv_JNI_PushLocalFrame relies on this right now.
277 _Jv_JNI_LocalFrame *frame;
280 frame = (_Jv_JNI_LocalFrame *) _Jv_Malloc (sizeof (_Jv_JNI_LocalFrame)
281 + size * sizeof (jobject));
283 catch (jthrowable t)
285 env->ex = t;
286 return JNI_ERR;
289 frame->marker = MARK_NONE;
290 frame->size = size;
291 memset (&frame->vec[0], 0, size * sizeof (jobject));
292 frame->next = env->locals;
293 env->locals = frame;
295 return 0;
298 static jint JNICALL
299 _Jv_JNI_PushLocalFrame (JNIEnv *env, jint size)
301 jint r = _Jv_JNI_EnsureLocalCapacity (env, size);
302 if (r < 0)
303 return r;
305 // The new frame is on top.
306 env->locals->marker = MARK_USER;
308 return 0;
311 static jobject JNICALL
312 _Jv_JNI_NewLocalRef (JNIEnv *env, jobject obj)
314 // This seems weird but I think it is correct.
315 obj = unwrap (obj);
317 // Try to find an open slot somewhere in the topmost frame.
318 _Jv_JNI_LocalFrame *frame = env->locals;
319 bool done = false, set = false;
320 for (; frame != NULL && ! done; frame = frame->next)
322 for (int i = 0; i < frame->size; ++i)
324 if (frame->vec[i] == NULL)
326 set = true;
327 done = true;
328 frame->vec[i] = obj;
329 break;
333 // If we found a slot, or if the frame we just searched is the
334 // mark frame, then we are done.
335 if (done || frame == NULL || frame->marker != MARK_NONE)
336 break;
339 if (! set)
341 // No slots, so we allocate a new frame. According to the spec
342 // we could just die here. FIXME: return value.
343 _Jv_JNI_EnsureLocalCapacity (env, 16);
344 // We know the first element of the new frame will be ok.
345 env->locals->vec[0] = obj;
348 mark_for_gc (obj, local_ref_table);
349 return obj;
352 static jobject JNICALL
353 _Jv_JNI_PopLocalFrame (JNIEnv *env, jobject result, int stop)
355 _Jv_JNI_LocalFrame *rf = env->locals;
357 bool done = false;
358 while (rf != NULL && ! done)
360 for (int i = 0; i < rf->size; ++i)
361 if (rf->vec[i] != NULL)
362 unmark_for_gc (rf->vec[i], local_ref_table);
364 // If the frame we just freed is the marker frame, we are done.
365 done = (rf->marker == stop);
367 _Jv_JNI_LocalFrame *n = rf->next;
368 // When N==NULL, we've reached the stack-allocated frame, and we
369 // must not free it. However, we must be sure to clear all its
370 // elements, since we might conceivably reuse it.
371 if (n == NULL)
373 memset (&rf->vec[0], 0, rf->size * sizeof (jobject));
374 break;
377 _Jv_Free (rf);
378 rf = n;
381 // Update the local frame information.
382 env->locals = rf;
384 return result == NULL ? NULL : _Jv_JNI_NewLocalRef (env, result);
387 static jobject JNICALL
388 _Jv_JNI_PopLocalFrame (JNIEnv *env, jobject result)
390 return _Jv_JNI_PopLocalFrame (env, result, MARK_USER);
393 // Make sure an array's type is compatible with the type of the
394 // destination.
395 template<typename T>
396 static bool
397 _Jv_JNI_check_types (JNIEnv *env, JArray<T> *array, jclass K)
399 jclass klass = array->getClass()->getComponentType();
400 if (__builtin_expect (klass != K, false))
402 env->ex = new java::lang::IllegalAccessError ();
403 return false;
405 else
406 return true;
409 // Pop a `system' frame from the stack. This is `extern "C"' as it is
410 // used by the compiler.
411 extern "C" void
412 _Jv_JNI_PopSystemFrame (JNIEnv *env)
414 _Jv_JNI_PopLocalFrame (env, NULL, MARK_SYSTEM);
416 if (env->ex)
418 jthrowable t = env->ex;
419 env->ex = NULL;
420 throw t;
424 template<typename T> T extract_from_jvalue(jvalue const & t);
425 template<> jboolean extract_from_jvalue(jvalue const & jv) { return jv.z; }
426 template<> jbyte extract_from_jvalue(jvalue const & jv) { return jv.b; }
427 template<> jchar extract_from_jvalue(jvalue const & jv) { return jv.c; }
428 template<> jshort extract_from_jvalue(jvalue const & jv) { return jv.s; }
429 template<> jint extract_from_jvalue(jvalue const & jv) { return jv.i; }
430 template<> jlong extract_from_jvalue(jvalue const & jv) { return jv.j; }
431 template<> jfloat extract_from_jvalue(jvalue const & jv) { return jv.f; }
432 template<> jdouble extract_from_jvalue(jvalue const & jv) { return jv.d; }
433 template<> jobject extract_from_jvalue(jvalue const & jv) { return jv.l; }
436 // This function is used from other template functions. It wraps the
437 // return value appropriately; we specialize it so that object returns
438 // are turned into local references.
439 template<typename T>
440 static T
441 wrap_value (JNIEnv *, T value)
443 return value;
446 // This specialization is used for jobject, jclass, jstring, jarray,
447 // etc.
448 template<typename R, typename T>
449 static T *
450 wrap_value (JNIEnv *env, T *value)
452 return (value == NULL
453 ? value
454 : (T *) _Jv_JNI_NewLocalRef (env, (jobject) value));
459 static jint JNICALL
460 _Jv_JNI_GetVersion (JNIEnv *)
462 return JNI_VERSION_1_4;
465 static jclass JNICALL
466 _Jv_JNI_DefineClass (JNIEnv *env, const char *name, jobject loader,
467 const jbyte *buf, jsize bufLen)
471 loader = unwrap (loader);
473 jstring sname = JvNewStringUTF (name);
474 jbyteArray bytes = JvNewByteArray (bufLen);
476 jbyte *elts = elements (bytes);
477 memcpy (elts, buf, bufLen * sizeof (jbyte));
479 java::lang::ClassLoader *l
480 = reinterpret_cast<java::lang::ClassLoader *> (loader);
482 jclass result = l->defineClass (sname, bytes, 0, bufLen);
483 return (jclass) wrap_value (env, result);
485 catch (jthrowable t)
487 env->ex = t;
488 return NULL;
492 static jclass JNICALL
493 _Jv_JNI_FindClass (JNIEnv *env, const char *name)
495 // FIXME: assume that NAME isn't too long.
496 int len = strlen (name);
497 char s[len + 1];
498 for (int i = 0; i <= len; ++i)
499 s[i] = (name[i] == '/') ? '.' : name[i];
501 jclass r = NULL;
504 // This might throw an out of memory exception.
505 jstring n = JvNewStringUTF (s);
507 java::lang::ClassLoader *loader = NULL;
508 if (env->klass != NULL)
509 loader = env->klass->getClassLoaderInternal ();
511 if (loader == NULL)
513 // FIXME: should use getBaseClassLoader, but we don't have that
514 // yet.
515 loader = java::lang::ClassLoader::getSystemClassLoader ();
518 r = loader->loadClass (n);
520 catch (jthrowable t)
522 env->ex = t;
525 return (jclass) wrap_value (env, r);
528 static jclass JNICALL
529 _Jv_JNI_GetSuperclass (JNIEnv *env, jclass clazz)
531 return (jclass) wrap_value (env, unwrap (clazz)->getSuperclass ());
534 static jboolean JNICALL
535 _Jv_JNI_IsAssignableFrom (JNIEnv *, jclass clazz1, jclass clazz2)
537 return unwrap (clazz1)->isAssignableFrom (unwrap (clazz2));
540 static jint JNICALL
541 _Jv_JNI_Throw (JNIEnv *env, jthrowable obj)
543 // We check in case the user did some funky cast.
544 obj = unwrap (obj);
545 JvAssert (obj != NULL && java::lang::Throwable::class$.isInstance (obj));
546 env->ex = obj;
547 return 0;
550 static jint JNICALL
551 _Jv_JNI_ThrowNew (JNIEnv *env, jclass clazz, const char *message)
553 using namespace java::lang::reflect;
555 clazz = unwrap (clazz);
556 JvAssert (java::lang::Throwable::class$.isAssignableFrom (clazz));
558 int r = JNI_OK;
561 JArray<jclass> *argtypes
562 = (JArray<jclass> *) JvNewObjectArray (1, &java::lang::Class::class$,
563 NULL);
565 jclass *elts = elements (argtypes);
566 elts[0] = &StringClass;
568 Constructor *cons = clazz->getConstructor (argtypes);
570 jobjectArray values = JvNewObjectArray (1, &StringClass, NULL);
571 jobject *velts = elements (values);
572 velts[0] = JvNewStringUTF (message);
574 jobject obj = cons->newInstance (values);
576 env->ex = reinterpret_cast<jthrowable> (obj);
578 catch (jthrowable t)
580 env->ex = t;
581 r = JNI_ERR;
584 return r;
587 static jthrowable JNICALL
588 _Jv_JNI_ExceptionOccurred (JNIEnv *env)
590 return (jthrowable) wrap_value (env, env->ex);
593 static void JNICALL
594 _Jv_JNI_ExceptionDescribe (JNIEnv *env)
596 if (env->ex != NULL)
597 env->ex->printStackTrace();
600 static void JNICALL
601 _Jv_JNI_ExceptionClear (JNIEnv *env)
603 env->ex = NULL;
606 static jboolean JNICALL
607 _Jv_JNI_ExceptionCheck (JNIEnv *env)
609 return env->ex != NULL;
612 static void JNICALL
613 _Jv_JNI_FatalError (JNIEnv *, const char *message)
615 JvFail (message);
620 static jboolean JNICALL
621 _Jv_JNI_IsSameObject (JNIEnv *, jobject obj1, jobject obj2)
623 return unwrap (obj1) == unwrap (obj2);
626 static jobject JNICALL
627 _Jv_JNI_AllocObject (JNIEnv *env, jclass clazz)
629 jobject obj = NULL;
630 using namespace java::lang::reflect;
634 clazz = unwrap (clazz);
635 JvAssert (clazz && ! clazz->isArray ());
636 if (clazz->isInterface() || Modifier::isAbstract(clazz->getModifiers()))
637 env->ex = new java::lang::InstantiationException ();
638 else
639 obj = _Jv_AllocObject (clazz);
641 catch (jthrowable t)
643 env->ex = t;
646 return wrap_value (env, obj);
649 static jclass JNICALL
650 _Jv_JNI_GetObjectClass (JNIEnv *env, jobject obj)
652 obj = unwrap (obj);
653 JvAssert (obj);
654 return (jclass) wrap_value (env, obj->getClass());
657 static jboolean JNICALL
658 _Jv_JNI_IsInstanceOf (JNIEnv *, jobject obj, jclass clazz)
660 return unwrap (clazz)->isInstance(unwrap (obj));
666 // This section concerns method invocation.
669 template<jboolean is_static>
670 static jmethodID JNICALL
671 _Jv_JNI_GetAnyMethodID (JNIEnv *env, jclass clazz,
672 const char *name, const char *sig)
676 clazz = unwrap (clazz);
677 _Jv_InitClass (clazz);
679 _Jv_Utf8Const *name_u = _Jv_makeUtf8Const ((char *) name, -1);
681 // FIXME: assume that SIG isn't too long.
682 int len = strlen (sig);
683 char s[len + 1];
684 for (int i = 0; i <= len; ++i)
685 s[i] = (sig[i] == '/') ? '.' : sig[i];
686 _Jv_Utf8Const *sig_u = _Jv_makeUtf8Const ((char *) s, -1);
688 JvAssert (! clazz->isPrimitive());
690 using namespace java::lang::reflect;
692 while (clazz != NULL)
694 jint count = JvNumMethods (clazz);
695 jmethodID meth = JvGetFirstMethod (clazz);
697 for (jint i = 0; i < count; ++i)
699 if (((is_static && Modifier::isStatic (meth->accflags))
700 || (! is_static && ! Modifier::isStatic (meth->accflags)))
701 && _Jv_equalUtf8Consts (meth->name, name_u)
702 && _Jv_equalUtf8Consts (meth->signature, sig_u))
703 return meth;
705 meth = meth->getNextMethod();
708 clazz = clazz->getSuperclass ();
711 java::lang::StringBuffer *name_sig =
712 new java::lang::StringBuffer (JvNewStringUTF (name));
713 name_sig->append ((jchar) ' ')->append (JvNewStringUTF (s));
714 env->ex = new java::lang::NoSuchMethodError (name_sig->toString ());
716 catch (jthrowable t)
718 env->ex = t;
721 return NULL;
724 // This is a helper function which turns a va_list into an array of
725 // `jvalue's. It needs signature information in order to do its work.
726 // The array of values must already be allocated.
727 static void
728 array_from_valist (jvalue *values, JArray<jclass> *arg_types, va_list vargs)
730 jclass *arg_elts = elements (arg_types);
731 for (int i = 0; i < arg_types->length; ++i)
733 // Here we assume that sizeof(int) >= sizeof(jint), because we
734 // use `int' when decoding the varargs. Likewise for
735 // float, and double. Also we assume that sizeof(jlong) >=
736 // sizeof(int), i.e. that jlong values are not further
737 // promoted.
738 JvAssert (sizeof (int) >= sizeof (jint));
739 JvAssert (sizeof (jlong) >= sizeof (int));
740 JvAssert (sizeof (double) >= sizeof (jfloat));
741 JvAssert (sizeof (double) >= sizeof (jdouble));
742 if (arg_elts[i] == JvPrimClass (byte))
743 values[i].b = (jbyte) va_arg (vargs, int);
744 else if (arg_elts[i] == JvPrimClass (short))
745 values[i].s = (jshort) va_arg (vargs, int);
746 else if (arg_elts[i] == JvPrimClass (int))
747 values[i].i = (jint) va_arg (vargs, int);
748 else if (arg_elts[i] == JvPrimClass (long))
749 values[i].j = (jlong) va_arg (vargs, jlong);
750 else if (arg_elts[i] == JvPrimClass (float))
751 values[i].f = (jfloat) va_arg (vargs, double);
752 else if (arg_elts[i] == JvPrimClass (double))
753 values[i].d = (jdouble) va_arg (vargs, double);
754 else if (arg_elts[i] == JvPrimClass (boolean))
755 values[i].z = (jboolean) va_arg (vargs, int);
756 else if (arg_elts[i] == JvPrimClass (char))
757 values[i].c = (jchar) va_arg (vargs, int);
758 else
760 // An object.
761 values[i].l = unwrap (va_arg (vargs, jobject));
766 // This can call any sort of method: virtual, "nonvirtual", static, or
767 // constructor.
768 template<typename T, invocation_type style>
769 static T JNICALL
770 _Jv_JNI_CallAnyMethodV (JNIEnv *env, jobject obj, jclass klass,
771 jmethodID id, va_list vargs)
773 obj = unwrap (obj);
774 klass = unwrap (klass);
776 jclass decl_class = klass ? klass : obj->getClass ();
777 JvAssert (decl_class != NULL);
779 jclass return_type;
780 JArray<jclass> *arg_types;
784 _Jv_GetTypesFromSignature (id, decl_class,
785 &arg_types, &return_type);
787 jvalue args[arg_types->length];
788 array_from_valist (args, arg_types, vargs);
790 // For constructors we need to pass the Class we are instantiating.
791 if (style == constructor)
792 return_type = klass;
794 jvalue result;
795 _Jv_CallAnyMethodA (obj, return_type, id,
796 style == constructor,
797 style == normal,
798 arg_types, args, &result);
800 return wrap_value (env, extract_from_jvalue<T>(result));
802 catch (jthrowable t)
804 env->ex = t;
807 return wrap_value (env, (T) 0);
810 template<typename T, invocation_type style>
811 static T JNICALL
812 _Jv_JNI_CallAnyMethod (JNIEnv *env, jobject obj, jclass klass,
813 jmethodID method, ...)
815 va_list args;
816 T result;
818 va_start (args, method);
819 result = _Jv_JNI_CallAnyMethodV<T, style> (env, obj, klass, method, args);
820 va_end (args);
822 return result;
825 template<typename T, invocation_type style>
826 static T JNICALL
827 _Jv_JNI_CallAnyMethodA (JNIEnv *env, jobject obj, jclass klass,
828 jmethodID id, jvalue *args)
830 obj = unwrap (obj);
831 klass = unwrap (klass);
833 jclass decl_class = klass ? klass : obj->getClass ();
834 JvAssert (decl_class != NULL);
836 jclass return_type;
837 JArray<jclass> *arg_types;
840 _Jv_GetTypesFromSignature (id, decl_class,
841 &arg_types, &return_type);
843 // For constructors we need to pass the Class we are instantiating.
844 if (style == constructor)
845 return_type = klass;
847 // Unwrap arguments as required. Eww.
848 jclass *type_elts = elements (arg_types);
849 jvalue arg_copy[arg_types->length];
850 for (int i = 0; i < arg_types->length; ++i)
852 if (type_elts[i]->isPrimitive ())
853 arg_copy[i] = args[i];
854 else
855 arg_copy[i].l = unwrap (args[i].l);
858 jvalue result;
859 _Jv_CallAnyMethodA (obj, return_type, id,
860 style == constructor,
861 style == normal,
862 arg_types, arg_copy, &result);
864 return wrap_value (env, extract_from_jvalue<T>(result));
866 catch (jthrowable t)
868 env->ex = t;
871 return wrap_value (env, (T) 0);
874 template<invocation_type style>
875 static void JNICALL
876 _Jv_JNI_CallAnyVoidMethodV (JNIEnv *env, jobject obj, jclass klass,
877 jmethodID id, va_list vargs)
879 obj = unwrap (obj);
880 klass = unwrap (klass);
882 jclass decl_class = klass ? klass : obj->getClass ();
883 JvAssert (decl_class != NULL);
885 jclass return_type;
886 JArray<jclass> *arg_types;
889 _Jv_GetTypesFromSignature (id, decl_class,
890 &arg_types, &return_type);
892 jvalue args[arg_types->length];
893 array_from_valist (args, arg_types, vargs);
895 // For constructors we need to pass the Class we are instantiating.
896 if (style == constructor)
897 return_type = klass;
899 _Jv_CallAnyMethodA (obj, return_type, id,
900 style == constructor,
901 style == normal,
902 arg_types, args, NULL);
904 catch (jthrowable t)
906 env->ex = t;
910 template<invocation_type style>
911 static void JNICALL
912 _Jv_JNI_CallAnyVoidMethod (JNIEnv *env, jobject obj, jclass klass,
913 jmethodID method, ...)
915 va_list args;
917 va_start (args, method);
918 _Jv_JNI_CallAnyVoidMethodV<style> (env, obj, klass, method, args);
919 va_end (args);
922 template<invocation_type style>
923 static void JNICALL
924 _Jv_JNI_CallAnyVoidMethodA (JNIEnv *env, jobject obj, jclass klass,
925 jmethodID id, jvalue *args)
927 jclass decl_class = klass ? klass : obj->getClass ();
928 JvAssert (decl_class != NULL);
930 jclass return_type;
931 JArray<jclass> *arg_types;
934 _Jv_GetTypesFromSignature (id, decl_class,
935 &arg_types, &return_type);
937 // Unwrap arguments as required. Eww.
938 jclass *type_elts = elements (arg_types);
939 jvalue arg_copy[arg_types->length];
940 for (int i = 0; i < arg_types->length; ++i)
942 if (type_elts[i]->isPrimitive ())
943 arg_copy[i] = args[i];
944 else
945 arg_copy[i].l = unwrap (args[i].l);
948 _Jv_CallAnyMethodA (obj, return_type, id,
949 style == constructor,
950 style == normal,
951 arg_types, args, NULL);
953 catch (jthrowable t)
955 env->ex = t;
959 // Functions with this signature are used to implement functions in
960 // the CallMethod family.
961 template<typename T>
962 static T JNICALL
963 _Jv_JNI_CallMethodV (JNIEnv *env, jobject obj,
964 jmethodID id, va_list args)
966 return _Jv_JNI_CallAnyMethodV<T, normal> (env, obj, NULL, id, args);
969 // Functions with this signature are used to implement functions in
970 // the CallMethod family.
971 template<typename T>
972 static T JNICALL
973 _Jv_JNI_CallMethod (JNIEnv *env, jobject obj, jmethodID id, ...)
975 va_list args;
976 T result;
978 va_start (args, id);
979 result = _Jv_JNI_CallAnyMethodV<T, normal> (env, obj, NULL, id, args);
980 va_end (args);
982 return result;
985 // Functions with this signature are used to implement functions in
986 // the CallMethod family.
987 template<typename T>
988 static T JNICALL
989 _Jv_JNI_CallMethodA (JNIEnv *env, jobject obj,
990 jmethodID id, jvalue *args)
992 return _Jv_JNI_CallAnyMethodA<T, normal> (env, obj, NULL, id, args);
995 static void JNICALL
996 _Jv_JNI_CallVoidMethodV (JNIEnv *env, jobject obj,
997 jmethodID id, va_list args)
999 _Jv_JNI_CallAnyVoidMethodV<normal> (env, obj, NULL, id, args);
1002 static void JNICALL
1003 _Jv_JNI_CallVoidMethod (JNIEnv *env, jobject obj, jmethodID id, ...)
1005 va_list args;
1007 va_start (args, id);
1008 _Jv_JNI_CallAnyVoidMethodV<normal> (env, obj, NULL, id, args);
1009 va_end (args);
1012 static void JNICALL
1013 _Jv_JNI_CallVoidMethodA (JNIEnv *env, jobject obj,
1014 jmethodID id, jvalue *args)
1016 _Jv_JNI_CallAnyVoidMethodA<normal> (env, obj, NULL, id, args);
1019 // Functions with this signature are used to implement functions in
1020 // the CallStaticMethod family.
1021 template<typename T>
1022 static T JNICALL
1023 _Jv_JNI_CallStaticMethodV (JNIEnv *env, jclass klass,
1024 jmethodID id, va_list args)
1026 JvAssert (((id->accflags) & java::lang::reflect::Modifier::STATIC));
1027 JvAssert (java::lang::Class::class$.isInstance (unwrap (klass)));
1029 return _Jv_JNI_CallAnyMethodV<T, static_type> (env, NULL, klass, id, args);
1032 // Functions with this signature are used to implement functions in
1033 // the CallStaticMethod family.
1034 template<typename T>
1035 static T JNICALL
1036 _Jv_JNI_CallStaticMethod (JNIEnv *env, jclass klass,
1037 jmethodID id, ...)
1039 va_list args;
1040 T result;
1042 JvAssert (((id->accflags) & java::lang::reflect::Modifier::STATIC));
1043 JvAssert (java::lang::Class::class$.isInstance (unwrap (klass)));
1045 va_start (args, id);
1046 result = _Jv_JNI_CallAnyMethodV<T, static_type> (env, NULL, klass,
1047 id, args);
1048 va_end (args);
1050 return result;
1053 // Functions with this signature are used to implement functions in
1054 // the CallStaticMethod family.
1055 template<typename T>
1056 static T JNICALL
1057 _Jv_JNI_CallStaticMethodA (JNIEnv *env, jclass klass, jmethodID id,
1058 jvalue *args)
1060 JvAssert (((id->accflags) & java::lang::reflect::Modifier::STATIC));
1061 JvAssert (java::lang::Class::class$.isInstance (unwrap (klass)));
1063 return _Jv_JNI_CallAnyMethodA<T, static_type> (env, NULL, klass, id, args);
1066 static void JNICALL
1067 _Jv_JNI_CallStaticVoidMethodV (JNIEnv *env, jclass klass,
1068 jmethodID id, va_list args)
1070 _Jv_JNI_CallAnyVoidMethodV<static_type> (env, NULL, klass, id, args);
1073 static void JNICALL
1074 _Jv_JNI_CallStaticVoidMethod (JNIEnv *env, jclass klass,
1075 jmethodID id, ...)
1077 va_list args;
1079 va_start (args, id);
1080 _Jv_JNI_CallAnyVoidMethodV<static_type> (env, NULL, klass, id, args);
1081 va_end (args);
1084 static void JNICALL
1085 _Jv_JNI_CallStaticVoidMethodA (JNIEnv *env, jclass klass,
1086 jmethodID id, jvalue *args)
1088 _Jv_JNI_CallAnyVoidMethodA<static_type> (env, NULL, klass, id, args);
1091 static jobject JNICALL
1092 _Jv_JNI_NewObjectV (JNIEnv *env, jclass klass,
1093 jmethodID id, va_list args)
1095 JvAssert (klass && ! klass->isArray ());
1096 JvAssert (! strcmp (id->name->data, "<init>")
1097 && id->signature->length > 2
1098 && id->signature->data[0] == '('
1099 && ! strcmp (&id->signature->data[id->signature->length - 2],
1100 ")V"));
1102 return _Jv_JNI_CallAnyMethodV<jobject, constructor> (env, NULL, klass,
1103 id, args);
1106 static jobject JNICALL
1107 _Jv_JNI_NewObject (JNIEnv *env, jclass klass, jmethodID id, ...)
1109 JvAssert (klass && ! klass->isArray ());
1110 JvAssert (! strcmp (id->name->data, "<init>")
1111 && id->signature->length > 2
1112 && id->signature->data[0] == '('
1113 && ! strcmp (&id->signature->data[id->signature->length - 2],
1114 ")V"));
1116 va_list args;
1117 jobject result;
1119 va_start (args, id);
1120 result = _Jv_JNI_CallAnyMethodV<jobject, constructor> (env, NULL, klass,
1121 id, args);
1122 va_end (args);
1124 return result;
1127 static jobject JNICALL
1128 _Jv_JNI_NewObjectA (JNIEnv *env, jclass klass, jmethodID id,
1129 jvalue *args)
1131 JvAssert (klass && ! klass->isArray ());
1132 JvAssert (! strcmp (id->name->data, "<init>")
1133 && id->signature->length > 2
1134 && id->signature->data[0] == '('
1135 && ! strcmp (&id->signature->data[id->signature->length - 2],
1136 ")V"));
1138 return _Jv_JNI_CallAnyMethodA<jobject, constructor> (env, NULL, klass,
1139 id, args);
1144 template<typename T>
1145 static T JNICALL
1146 _Jv_JNI_GetField (JNIEnv *env, jobject obj, jfieldID field)
1148 obj = unwrap (obj);
1149 JvAssert (obj);
1150 T *ptr = (T *) ((char *) obj + field->getOffset ());
1151 return wrap_value (env, *ptr);
1154 template<typename T>
1155 static void JNICALL
1156 _Jv_JNI_SetField (JNIEnv *, jobject obj, jfieldID field, T value)
1158 obj = unwrap (obj);
1159 value = unwrap (value);
1161 JvAssert (obj);
1162 T *ptr = (T *) ((char *) obj + field->getOffset ());
1163 *ptr = value;
1166 template<jboolean is_static>
1167 static jfieldID JNICALL
1168 _Jv_JNI_GetAnyFieldID (JNIEnv *env, jclass clazz,
1169 const char *name, const char *sig)
1173 clazz = unwrap (clazz);
1175 _Jv_InitClass (clazz);
1177 _Jv_Utf8Const *a_name = _Jv_makeUtf8Const ((char *) name, -1);
1179 // FIXME: assume that SIG isn't too long.
1180 int len = strlen (sig);
1181 char s[len + 1];
1182 for (int i = 0; i <= len; ++i)
1183 s[i] = (sig[i] == '/') ? '.' : sig[i];
1184 jclass field_class = _Jv_FindClassFromSignature ((char *) s, NULL);
1186 // FIXME: what if field_class == NULL?
1188 java::lang::ClassLoader *loader = clazz->getClassLoaderInternal ();
1189 while (clazz != NULL)
1191 // We acquire the class lock so that fields aren't resolved
1192 // while we are running.
1193 JvSynchronize sync (clazz);
1195 jint count = (is_static
1196 ? JvNumStaticFields (clazz)
1197 : JvNumInstanceFields (clazz));
1198 jfieldID field = (is_static
1199 ? JvGetFirstStaticField (clazz)
1200 : JvGetFirstInstanceField (clazz));
1201 for (jint i = 0; i < count; ++i)
1203 _Jv_Utf8Const *f_name = field->getNameUtf8Const(clazz);
1205 // The field might be resolved or it might not be. It
1206 // is much simpler to always resolve it.
1207 _Jv_ResolveField (field, loader);
1208 if (_Jv_equalUtf8Consts (f_name, a_name)
1209 && field->getClass() == field_class)
1210 return field;
1212 field = field->getNextField ();
1215 clazz = clazz->getSuperclass ();
1218 env->ex = new java::lang::NoSuchFieldError ();
1220 catch (jthrowable t)
1222 env->ex = t;
1224 return NULL;
1227 template<typename T>
1228 static T JNICALL
1229 _Jv_JNI_GetStaticField (JNIEnv *env, jclass, jfieldID field)
1231 T *ptr = (T *) field->u.addr;
1232 return wrap_value (env, *ptr);
1235 template<typename T>
1236 static void JNICALL
1237 _Jv_JNI_SetStaticField (JNIEnv *, jclass, jfieldID field, T value)
1239 value = unwrap (value);
1240 T *ptr = (T *) field->u.addr;
1241 *ptr = value;
1244 static jstring JNICALL
1245 _Jv_JNI_NewString (JNIEnv *env, const jchar *unichars, jsize len)
1249 jstring r = _Jv_NewString (unichars, len);
1250 return (jstring) wrap_value (env, r);
1252 catch (jthrowable t)
1254 env->ex = t;
1255 return NULL;
1259 static jsize JNICALL
1260 _Jv_JNI_GetStringLength (JNIEnv *, jstring string)
1262 return unwrap (string)->length();
1265 static const jchar * JNICALL
1266 _Jv_JNI_GetStringChars (JNIEnv *, jstring string, jboolean *isCopy)
1268 string = unwrap (string);
1269 jchar *result = _Jv_GetStringChars (string);
1270 mark_for_gc (string, global_ref_table);
1271 if (isCopy)
1272 *isCopy = false;
1273 return (const jchar *) result;
1276 static void JNICALL
1277 _Jv_JNI_ReleaseStringChars (JNIEnv *, jstring string, const jchar *)
1279 unmark_for_gc (unwrap (string), global_ref_table);
1282 static jstring JNICALL
1283 _Jv_JNI_NewStringUTF (JNIEnv *env, const char *bytes)
1287 jstring result = JvNewStringUTF (bytes);
1288 return (jstring) wrap_value (env, result);
1290 catch (jthrowable t)
1292 env->ex = t;
1293 return NULL;
1297 static jsize JNICALL
1298 _Jv_JNI_GetStringUTFLength (JNIEnv *, jstring string)
1300 return JvGetStringUTFLength (unwrap (string));
1303 static const char * JNICALL
1304 _Jv_JNI_GetStringUTFChars (JNIEnv *env, jstring string,
1305 jboolean *isCopy)
1309 string = unwrap (string);
1310 if (string == NULL)
1311 return NULL;
1312 jsize len = JvGetStringUTFLength (string);
1313 char *r = (char *) _Jv_Malloc (len + 1);
1314 JvGetStringUTFRegion (string, 0, string->length(), r);
1315 r[len] = '\0';
1317 if (isCopy)
1318 *isCopy = true;
1320 return (const char *) r;
1322 catch (jthrowable t)
1324 env->ex = t;
1325 return NULL;
1329 static void JNICALL
1330 _Jv_JNI_ReleaseStringUTFChars (JNIEnv *, jstring, const char *utf)
1332 _Jv_Free ((void *) utf);
1335 static void JNICALL
1336 _Jv_JNI_GetStringRegion (JNIEnv *env, jstring string, jsize start,
1337 jsize len, jchar *buf)
1339 string = unwrap (string);
1340 jchar *result = _Jv_GetStringChars (string);
1341 if (start < 0 || start > string->length ()
1342 || len < 0 || start + len > string->length ())
1346 env->ex = new java::lang::StringIndexOutOfBoundsException ();
1348 catch (jthrowable t)
1350 env->ex = t;
1353 else
1354 memcpy (buf, &result[start], len * sizeof (jchar));
1357 static void JNICALL
1358 _Jv_JNI_GetStringUTFRegion (JNIEnv *env, jstring str, jsize start,
1359 jsize len, char *buf)
1361 str = unwrap (str);
1363 if (start < 0 || start > str->length ()
1364 || len < 0 || start + len > str->length ())
1368 env->ex = new java::lang::StringIndexOutOfBoundsException ();
1370 catch (jthrowable t)
1372 env->ex = t;
1375 else
1376 _Jv_GetStringUTFRegion (str, start, len, buf);
1379 static const jchar * JNICALL
1380 _Jv_JNI_GetStringCritical (JNIEnv *, jstring str, jboolean *isCopy)
1382 jchar *result = _Jv_GetStringChars (unwrap (str));
1383 if (isCopy)
1384 *isCopy = false;
1385 return result;
1388 static void JNICALL
1389 _Jv_JNI_ReleaseStringCritical (JNIEnv *, jstring, const jchar *)
1391 // Nothing.
1394 static jsize JNICALL
1395 _Jv_JNI_GetArrayLength (JNIEnv *, jarray array)
1397 return unwrap (array)->length;
1400 static jobjectArray JNICALL
1401 _Jv_JNI_NewObjectArray (JNIEnv *env, jsize length,
1402 jclass elementClass, jobject init)
1406 elementClass = unwrap (elementClass);
1407 init = unwrap (init);
1409 _Jv_CheckCast (elementClass, init);
1410 jarray result = JvNewObjectArray (length, elementClass, init);
1411 return (jobjectArray) wrap_value (env, result);
1413 catch (jthrowable t)
1415 env->ex = t;
1416 return NULL;
1420 static jobject JNICALL
1421 _Jv_JNI_GetObjectArrayElement (JNIEnv *env, jobjectArray array,
1422 jsize index)
1424 if ((unsigned) index >= (unsigned) array->length)
1425 _Jv_ThrowBadArrayIndex (index);
1426 jobject *elts = elements (unwrap (array));
1427 return wrap_value (env, elts[index]);
1430 static void JNICALL
1431 _Jv_JNI_SetObjectArrayElement (JNIEnv *env, jobjectArray array,
1432 jsize index, jobject value)
1436 array = unwrap (array);
1437 value = unwrap (value);
1439 _Jv_CheckArrayStore (array, value);
1440 if ((unsigned) index >= (unsigned) array->length)
1441 _Jv_ThrowBadArrayIndex (index);
1442 jobject *elts = elements (array);
1443 elts[index] = value;
1445 catch (jthrowable t)
1447 env->ex = t;
1451 template<typename T, jclass K>
1452 static JArray<T> * JNICALL
1453 _Jv_JNI_NewPrimitiveArray (JNIEnv *env, jsize length)
1457 return (JArray<T> *) wrap_value (env, _Jv_NewPrimArray (K, length));
1459 catch (jthrowable t)
1461 env->ex = t;
1462 return NULL;
1466 template<typename T, jclass K>
1467 static T * JNICALL
1468 _Jv_JNI_GetPrimitiveArrayElements (JNIEnv *env, JArray<T> *array,
1469 jboolean *isCopy)
1471 array = unwrap (array);
1472 if (! _Jv_JNI_check_types (env, array, K))
1473 return NULL;
1474 T *elts = elements (array);
1475 if (isCopy)
1477 // We elect never to copy.
1478 *isCopy = false;
1480 mark_for_gc (array, global_ref_table);
1481 return elts;
1484 template<typename T, jclass K>
1485 static void JNICALL
1486 _Jv_JNI_ReleasePrimitiveArrayElements (JNIEnv *env, JArray<T> *array,
1487 T *, jint /* mode */)
1489 array = unwrap (array);
1490 _Jv_JNI_check_types (env, array, K);
1491 // Note that we ignore MODE. We can do this because we never copy
1492 // the array elements. My reading of the JNI documentation is that
1493 // this is an option for the implementor.
1494 unmark_for_gc (array, global_ref_table);
1497 template<typename T, jclass K>
1498 static void JNICALL
1499 _Jv_JNI_GetPrimitiveArrayRegion (JNIEnv *env, JArray<T> *array,
1500 jsize start, jsize len,
1501 T *buf)
1503 array = unwrap (array);
1504 if (! _Jv_JNI_check_types (env, array, K))
1505 return;
1507 // The cast to unsigned lets us save a comparison.
1508 if (start < 0 || len < 0
1509 || (unsigned long) (start + len) > (unsigned long) array->length)
1513 // FIXME: index.
1514 env->ex = new java::lang::ArrayIndexOutOfBoundsException ();
1516 catch (jthrowable t)
1518 // Could have thown out of memory error.
1519 env->ex = t;
1522 else
1524 T *elts = elements (array) + start;
1525 memcpy (buf, elts, len * sizeof (T));
1529 template<typename T, jclass K>
1530 static void JNICALL
1531 _Jv_JNI_SetPrimitiveArrayRegion (JNIEnv *env, JArray<T> *array,
1532 jsize start, jsize len, T *buf)
1534 array = unwrap (array);
1535 if (! _Jv_JNI_check_types (env, array, K))
1536 return;
1538 // The cast to unsigned lets us save a comparison.
1539 if (start < 0 || len < 0
1540 || (unsigned long) (start + len) > (unsigned long) array->length)
1544 // FIXME: index.
1545 env->ex = new java::lang::ArrayIndexOutOfBoundsException ();
1547 catch (jthrowable t)
1549 env->ex = t;
1552 else
1554 T *elts = elements (array) + start;
1555 memcpy (elts, buf, len * sizeof (T));
1559 static void * JNICALL
1560 _Jv_JNI_GetPrimitiveArrayCritical (JNIEnv *, jarray array,
1561 jboolean *isCopy)
1563 array = unwrap (array);
1564 // FIXME: does this work?
1565 jclass klass = array->getClass()->getComponentType();
1566 JvAssert (klass->isPrimitive ());
1567 char *r = _Jv_GetArrayElementFromElementType (array, klass);
1568 if (isCopy)
1569 *isCopy = false;
1570 return r;
1573 static void JNICALL
1574 _Jv_JNI_ReleasePrimitiveArrayCritical (JNIEnv *, jarray, void *, jint)
1576 // Nothing.
1579 static jint JNICALL
1580 _Jv_JNI_MonitorEnter (JNIEnv *env, jobject obj)
1584 _Jv_MonitorEnter (unwrap (obj));
1585 return 0;
1587 catch (jthrowable t)
1589 env->ex = t;
1591 return JNI_ERR;
1594 static jint JNICALL
1595 _Jv_JNI_MonitorExit (JNIEnv *env, jobject obj)
1599 _Jv_MonitorExit (unwrap (obj));
1600 return 0;
1602 catch (jthrowable t)
1604 env->ex = t;
1606 return JNI_ERR;
1609 // JDK 1.2
1610 jobject JNICALL
1611 _Jv_JNI_ToReflectedField (JNIEnv *env, jclass cls, jfieldID fieldID,
1612 jboolean)
1616 cls = unwrap (cls);
1617 java::lang::reflect::Field *field = new java::lang::reflect::Field();
1618 field->declaringClass = cls;
1619 field->offset = (char*) fieldID - (char *) cls->fields;
1620 field->name = _Jv_NewStringUtf8Const (fieldID->getNameUtf8Const (cls));
1621 return wrap_value (env, field);
1623 catch (jthrowable t)
1625 env->ex = t;
1627 return NULL;
1630 // JDK 1.2
1631 static jfieldID JNICALL
1632 _Jv_JNI_FromReflectedField (JNIEnv *, jobject f)
1634 using namespace java::lang::reflect;
1636 f = unwrap (f);
1637 Field *field = reinterpret_cast<Field *> (f);
1638 return _Jv_FromReflectedField (field);
1641 jobject JNICALL
1642 _Jv_JNI_ToReflectedMethod (JNIEnv *env, jclass klass, jmethodID id,
1643 jboolean)
1645 using namespace java::lang::reflect;
1647 jobject result = NULL;
1648 klass = unwrap (klass);
1652 if (_Jv_equalUtf8Consts (id->name, init_name))
1654 // A constructor.
1655 Constructor *cons = new Constructor ();
1656 cons->offset = (char *) id - (char *) &klass->methods;
1657 cons->declaringClass = klass;
1658 result = cons;
1660 else
1662 Method *meth = new Method ();
1663 meth->offset = (char *) id - (char *) &klass->methods;
1664 meth->declaringClass = klass;
1665 result = meth;
1668 catch (jthrowable t)
1670 env->ex = t;
1673 return wrap_value (env, result);
1676 static jmethodID JNICALL
1677 _Jv_JNI_FromReflectedMethod (JNIEnv *, jobject method)
1679 using namespace java::lang::reflect;
1680 method = unwrap (method);
1681 if (Method::class$.isInstance (method))
1682 return _Jv_FromReflectedMethod (reinterpret_cast<Method *> (method));
1683 return
1684 _Jv_FromReflectedConstructor (reinterpret_cast<Constructor *> (method));
1687 // JDK 1.2.
1688 jweak JNICALL
1689 _Jv_JNI_NewWeakGlobalRef (JNIEnv *env, jobject obj)
1691 using namespace gnu::gcj::runtime;
1692 JNIWeakRef *ref = NULL;
1696 // This seems weird but I think it is correct.
1697 obj = unwrap (obj);
1698 ref = new JNIWeakRef (obj);
1699 mark_for_gc (ref, global_ref_table);
1701 catch (jthrowable t)
1703 env->ex = t;
1706 return reinterpret_cast<jweak> (ref);
1709 void JNICALL
1710 _Jv_JNI_DeleteWeakGlobalRef (JNIEnv *, jweak obj)
1712 using namespace gnu::gcj::runtime;
1713 JNIWeakRef *ref = reinterpret_cast<JNIWeakRef *> (obj);
1714 unmark_for_gc (ref, global_ref_table);
1715 ref->clear ();
1720 // Direct byte buffers.
1722 static jobject JNICALL
1723 _Jv_JNI_NewDirectByteBuffer (JNIEnv *, void *address, jlong length)
1725 using namespace gnu::gcj;
1726 using namespace java::nio;
1727 return new DirectByteBufferImpl$ReadWrite
1728 (reinterpret_cast<RawData *> (address), length);
1731 static void * JNICALL
1732 _Jv_JNI_GetDirectBufferAddress (JNIEnv *, jobject buffer)
1734 using namespace java::nio;
1735 DirectByteBufferImpl* bb = static_cast<DirectByteBufferImpl *> (buffer);
1736 return reinterpret_cast<void *> (bb->address);
1739 static jlong JNICALL
1740 _Jv_JNI_GetDirectBufferCapacity (JNIEnv *, jobject buffer)
1742 using namespace java::nio;
1743 DirectByteBufferImpl* bb = static_cast<DirectByteBufferImpl *> (buffer);
1744 return bb->capacity();
1749 // Hash table of native methods.
1750 static JNINativeMethod *nathash;
1751 // Number of slots used.
1752 static int nathash_count = 0;
1753 // Number of slots available. Must be power of 2.
1754 static int nathash_size = 0;
1756 #define DELETED_ENTRY ((char *) (~0))
1758 // Compute a hash value for a native method descriptor.
1759 static int
1760 hash (const JNINativeMethod *method)
1762 char *ptr;
1763 int hash = 0;
1765 ptr = method->name;
1766 while (*ptr)
1767 hash = (31 * hash) + *ptr++;
1769 ptr = method->signature;
1770 while (*ptr)
1771 hash = (31 * hash) + *ptr++;
1773 return hash;
1776 // Find the slot where a native method goes.
1777 static JNINativeMethod *
1778 nathash_find_slot (const JNINativeMethod *method)
1780 jint h = hash (method);
1781 int step = (h ^ (h >> 16)) | 1;
1782 int w = h & (nathash_size - 1);
1783 int del = -1;
1785 for (;;)
1787 JNINativeMethod *slotp = &nathash[w];
1788 if (slotp->name == NULL)
1790 if (del >= 0)
1791 return &nathash[del];
1792 else
1793 return slotp;
1795 else if (slotp->name == DELETED_ENTRY)
1796 del = w;
1797 else if (! strcmp (slotp->name, method->name)
1798 && ! strcmp (slotp->signature, method->signature))
1799 return slotp;
1800 w = (w + step) & (nathash_size - 1);
1804 // Find a method. Return NULL if it isn't in the hash table.
1805 static void *
1806 nathash_find (JNINativeMethod *method)
1808 if (nathash == NULL)
1809 return NULL;
1810 JNINativeMethod *slot = nathash_find_slot (method);
1811 if (slot->name == NULL || slot->name == DELETED_ENTRY)
1812 return NULL;
1813 return slot->fnPtr;
1816 static void
1817 natrehash ()
1819 if (nathash == NULL)
1821 nathash_size = 1024;
1822 nathash =
1823 (JNINativeMethod *) _Jv_AllocBytes (nathash_size
1824 * sizeof (JNINativeMethod));
1825 memset (nathash, 0, nathash_size * sizeof (JNINativeMethod));
1827 else
1829 int savesize = nathash_size;
1830 JNINativeMethod *savehash = nathash;
1831 nathash_size *= 2;
1832 nathash =
1833 (JNINativeMethod *) _Jv_AllocBytes (nathash_size
1834 * sizeof (JNINativeMethod));
1835 memset (nathash, 0, nathash_size * sizeof (JNINativeMethod));
1837 for (int i = 0; i < savesize; ++i)
1839 if (savehash[i].name != NULL && savehash[i].name != DELETED_ENTRY)
1841 JNINativeMethod *slot = nathash_find_slot (&savehash[i]);
1842 *slot = savehash[i];
1848 static void
1849 nathash_add (const JNINativeMethod *method)
1851 if (3 * nathash_count >= 2 * nathash_size)
1852 natrehash ();
1853 JNINativeMethod *slot = nathash_find_slot (method);
1854 // If the slot has a real entry in it, then there is no work to do.
1855 if (slot->name != NULL && slot->name != DELETED_ENTRY)
1856 return;
1857 // FIXME
1858 slot->name = strdup (method->name);
1859 slot->signature = strdup (method->signature);
1860 slot->fnPtr = method->fnPtr;
1863 static jint JNICALL
1864 _Jv_JNI_RegisterNatives (JNIEnv *env, jclass klass,
1865 const JNINativeMethod *methods,
1866 jint nMethods)
1868 // Synchronize while we do the work. This must match
1869 // synchronization in some other functions that manipulate or use
1870 // the nathash table.
1871 JvSynchronize sync (global_ref_table);
1873 // Look at each descriptor given us, and find the corresponding
1874 // method in the class.
1875 for (int j = 0; j < nMethods; ++j)
1877 bool found = false;
1879 _Jv_Method *imeths = JvGetFirstMethod (klass);
1880 for (int i = 0; i < JvNumMethods (klass); ++i)
1882 _Jv_Method *self = &imeths[i];
1884 if (! strcmp (self->name->chars (), methods[j].name)
1885 && ! strcmp (self->signature->chars (), methods[j].signature))
1887 if (! (self->accflags & java::lang::reflect::Modifier::NATIVE))
1888 break;
1890 // Found a match that is native.
1891 found = true;
1892 nathash_add (&methods[j]);
1894 break;
1898 if (! found)
1900 jstring m = JvNewStringUTF (methods[j].name);
1903 env->ex = new java::lang::NoSuchMethodError (m);
1905 catch (jthrowable t)
1907 env->ex = t;
1909 return JNI_ERR;
1913 return JNI_OK;
1916 static jint JNICALL
1917 _Jv_JNI_UnregisterNatives (JNIEnv *, jclass)
1919 // FIXME -- we could implement this.
1920 return JNI_ERR;
1925 // Add a character to the buffer, encoding properly.
1926 static void
1927 add_char (char *buf, jchar c, int *here)
1929 if (c == '_')
1931 buf[(*here)++] = '_';
1932 buf[(*here)++] = '1';
1934 else if (c == ';')
1936 buf[(*here)++] = '_';
1937 buf[(*here)++] = '2';
1939 else if (c == '[')
1941 buf[(*here)++] = '_';
1942 buf[(*here)++] = '3';
1945 // Also check for `.' here because we might be passed an internal
1946 // qualified class name like `foo.bar'.
1947 else if (c == '/' || c == '.')
1948 buf[(*here)++] = '_';
1949 else if ((c >= '0' && c <= '9')
1950 || (c >= 'a' && c <= 'z')
1951 || (c >= 'A' && c <= 'Z'))
1952 buf[(*here)++] = (char) c;
1953 else
1955 // "Unicode" character.
1956 buf[(*here)++] = '_';
1957 buf[(*here)++] = '0';
1958 for (int i = 0; i < 4; ++i)
1960 int val = c & 0x0f;
1961 buf[(*here) + 3 - i] = (val > 10) ? ('a' + val - 10) : ('0' + val);
1962 c >>= 4;
1964 *here += 4;
1968 // Compute a mangled name for a native function. This computes the
1969 // long name, and also returns an index which indicates where a NUL
1970 // can be placed to create the short name. This function assumes that
1971 // the buffer is large enough for its results.
1972 static void
1973 mangled_name (jclass klass, _Jv_Utf8Const *func_name,
1974 _Jv_Utf8Const *signature, char *buf, int *long_start)
1976 strcpy (buf, "Java_");
1977 int here = 5;
1979 // Add fully qualified class name.
1980 jchar *chars = _Jv_GetStringChars (klass->getName ());
1981 jint len = klass->getName ()->length ();
1982 for (int i = 0; i < len; ++i)
1983 add_char (buf, chars[i], &here);
1985 // Don't use add_char because we need a literal `_'.
1986 buf[here++] = '_';
1988 const unsigned char *fn = (const unsigned char *) func_name->chars ();
1989 const unsigned char *limit = fn + func_name->len ();
1990 for (int i = 0; ; ++i)
1992 int ch = UTF8_GET (fn, limit);
1993 if (ch < 0)
1994 break;
1995 add_char (buf, ch, &here);
1998 // This is where the long signature begins.
1999 *long_start = here;
2000 buf[here++] = '_';
2001 buf[here++] = '_';
2003 const unsigned char *sig = (const unsigned char *) signature->chars ();
2004 limit = sig + signature->len ();
2005 JvAssert (sig[0] == '(');
2006 ++sig;
2007 while (1)
2009 int ch = UTF8_GET (sig, limit);
2010 if (ch == ')' || ch < 0)
2011 break;
2012 add_char (buf, ch, &here);
2015 buf[here] = '\0';
2018 // Return the current thread's JNIEnv; if one does not exist, create
2019 // it. Also create a new system frame for use. This is `extern "C"'
2020 // because the compiler calls it.
2021 extern "C" JNIEnv *
2022 _Jv_GetJNIEnvNewFrame (jclass klass)
2024 JNIEnv *env = _Jv_GetCurrentJNIEnv ();
2025 if (env == NULL)
2027 env = (JNIEnv *) _Jv_MallocUnchecked (sizeof (JNIEnv));
2028 env->p = &_Jv_JNIFunctions;
2029 env->klass = klass;
2030 env->locals = NULL;
2031 // We set env->ex below.
2033 _Jv_SetCurrentJNIEnv (env);
2036 _Jv_JNI_LocalFrame *frame
2037 = (_Jv_JNI_LocalFrame *) _Jv_MallocUnchecked (sizeof (_Jv_JNI_LocalFrame)
2038 + (FRAME_SIZE
2039 * sizeof (jobject)));
2041 frame->marker = MARK_SYSTEM;
2042 frame->size = FRAME_SIZE;
2043 frame->next = env->locals;
2045 for (int i = 0; i < frame->size; ++i)
2046 frame->vec[i] = NULL;
2048 env->locals = frame;
2049 env->ex = NULL;
2051 return env;
2054 // Return the function which implements a particular JNI method. If
2055 // we can't find the function, we throw the appropriate exception.
2056 // This is `extern "C"' because the compiler uses it.
2057 extern "C" void *
2058 _Jv_LookupJNIMethod (jclass klass, _Jv_Utf8Const *name,
2059 _Jv_Utf8Const *signature, MAYBE_UNUSED int args_size)
2061 int name_length = name->len();
2062 int sig_length = signature->len();
2063 char buf[10 + 6 * (name_length + sig_length) + 12];
2064 int long_start;
2065 void *function;
2067 // Synchronize on something convenient. Right now we use the hash.
2068 JvSynchronize sync (global_ref_table);
2070 // First see if we have an override in the hash table.
2071 strncpy (buf, name->chars (), name_length);
2072 buf[name_length] = '\0';
2073 strncpy (buf + name_length + 1, signature->chars (), sig_length);
2074 buf[name_length + sig_length + 1] = '\0';
2075 JNINativeMethod meth;
2076 meth.name = buf;
2077 meth.signature = buf + name_length + 1;
2078 function = nathash_find (&meth);
2079 if (function != NULL)
2080 return function;
2082 // If there was no override, then look in the symbol table.
2083 buf[0] = '_';
2084 mangled_name (klass, name, signature, buf + 1, &long_start);
2085 char c = buf[long_start + 1];
2086 buf[long_start + 1] = '\0';
2088 function = _Jv_FindSymbolInExecutable (buf + 1);
2089 #ifdef WIN32
2090 // On Win32, we use the "stdcall" calling convention (see JNICALL
2091 // in jni.h).
2093 // For a function named 'fooBar' that takes 'nn' bytes as arguments,
2094 // by default, MinGW GCC exports it as 'fooBar@nn', MSVC exports it
2095 // as '_fooBar@nn' and Borland C exports it as 'fooBar'. We try to
2096 // take care of all these variations here.
2098 char asz_buf[12]; /* '@' + '2147483647' (32-bit INT_MAX) + '\0' */
2099 char long_nm_sv[11]; /* Ditto, except for the '\0'. */
2101 if (function == NULL)
2103 // We have tried searching for the 'fooBar' form (BCC) - now
2104 // try the others.
2106 // First, save the part of the long name that will be damaged
2107 // by appending '@nn'.
2108 memcpy (long_nm_sv, (buf + long_start + 1 + 1), sizeof (long_nm_sv));
2110 sprintf (asz_buf, "@%d", args_size);
2111 strcat (buf, asz_buf);
2113 // Search for the '_fooBar@nn' form (MSVC).
2114 function = _Jv_FindSymbolInExecutable (buf);
2116 if (function == NULL)
2118 // Search for the 'fooBar@nn' form (MinGW GCC).
2119 function = _Jv_FindSymbolInExecutable (buf + 1);
2122 #endif /* WIN32 */
2124 if (function == NULL)
2126 buf[long_start + 1] = c;
2127 #ifdef WIN32
2128 // Restore the part of the long name that was damaged by
2129 // appending the '@nn'.
2130 memcpy ((buf + long_start + 1 + 1), long_nm_sv, sizeof (long_nm_sv));
2131 #endif /* WIN32 */
2132 function = _Jv_FindSymbolInExecutable (buf + 1);
2133 if (function == NULL)
2135 #ifdef WIN32
2136 strcat (buf, asz_buf);
2137 function = _Jv_FindSymbolInExecutable (buf);
2138 if (function == NULL)
2139 function = _Jv_FindSymbolInExecutable (buf + 1);
2141 if (function == NULL)
2142 #endif /* WIN32 */
2144 jstring str = JvNewStringUTF (name->chars ());
2145 throw new java::lang::UnsatisfiedLinkError (str);
2150 return function;
2153 #ifdef INTERPRETER
2155 // This function is the stub which is used to turn an ordinary (CNI)
2156 // method call into a JNI call.
2157 void
2158 _Jv_JNIMethod::call (ffi_cif *, void *ret, ffi_raw *args, void *__this)
2160 _Jv_JNIMethod* _this = (_Jv_JNIMethod *) __this;
2162 JNIEnv *env = _Jv_GetJNIEnvNewFrame (_this->defining_class);
2164 // FIXME: we should mark every reference parameter as a local. For
2165 // now we assume a conservative GC, and we assume that the
2166 // references are on the stack somewhere.
2168 // We cache the value that we find, of course, but if we don't find
2169 // a value we don't cache that fact -- we might subsequently load a
2170 // library which finds the function in question.
2172 // Synchronize on a convenient object to ensure sanity in case two
2173 // threads reach this point for the same function at the same
2174 // time.
2175 JvSynchronize sync (global_ref_table);
2176 if (_this->function == NULL)
2178 int args_size = sizeof (JNIEnv *) + _this->args_raw_size;
2180 if (_this->self->accflags & java::lang::reflect::Modifier::STATIC)
2181 args_size += sizeof (_this->defining_class);
2183 _this->function = _Jv_LookupJNIMethod (_this->defining_class,
2184 _this->self->name,
2185 _this->self->signature,
2186 args_size);
2190 JvAssert (_this->args_raw_size % sizeof (ffi_raw) == 0);
2191 ffi_raw real_args[2 + _this->args_raw_size / sizeof (ffi_raw)];
2192 int offset = 0;
2194 // First argument is always the environment pointer.
2195 real_args[offset++].ptr = env;
2197 // For a static method, we pass in the Class. For non-static
2198 // methods, the `this' argument is already handled.
2199 if ((_this->self->accflags & java::lang::reflect::Modifier::STATIC))
2200 real_args[offset++].ptr = _this->defining_class;
2202 // In libgcj, the callee synchronizes.
2203 jobject sync = NULL;
2204 if ((_this->self->accflags & java::lang::reflect::Modifier::SYNCHRONIZED))
2206 if ((_this->self->accflags & java::lang::reflect::Modifier::STATIC))
2207 sync = _this->defining_class;
2208 else
2209 sync = (jobject) args[0].ptr;
2210 _Jv_MonitorEnter (sync);
2213 // Copy over passed-in arguments.
2214 memcpy (&real_args[offset], args, _this->args_raw_size);
2216 // The actual call to the JNI function.
2217 #if FFI_NATIVE_RAW_API
2218 ffi_raw_call (&_this->jni_cif, (void (*)()) _this->function,
2219 ret, real_args);
2220 #else
2221 ffi_java_raw_call (&_this->jni_cif, (void (*)()) _this->function,
2222 ret, real_args);
2223 #endif
2225 if (sync != NULL)
2226 _Jv_MonitorExit (sync);
2228 _Jv_JNI_PopSystemFrame (env);
2231 #endif /* INTERPRETER */
2236 // Invocation API.
2239 // An internal helper function.
2240 static jint
2241 _Jv_JNI_AttachCurrentThread (JavaVM *, jstring name, void **penv,
2242 void *args, jboolean is_daemon)
2244 JavaVMAttachArgs *attach = reinterpret_cast<JavaVMAttachArgs *> (args);
2245 java::lang::ThreadGroup *group = NULL;
2247 if (attach)
2249 // FIXME: do we really want to support 1.1?
2250 if (attach->version != JNI_VERSION_1_4
2251 && attach->version != JNI_VERSION_1_2
2252 && attach->version != JNI_VERSION_1_1)
2253 return JNI_EVERSION;
2255 JvAssert (java::lang::ThreadGroup::class$.isInstance (attach->group));
2256 group = reinterpret_cast<java::lang::ThreadGroup *> (attach->group);
2259 // Attaching an already-attached thread is a no-op.
2260 if (_Jv_GetCurrentJNIEnv () != NULL)
2261 return 0;
2263 JNIEnv *env = (JNIEnv *) _Jv_MallocUnchecked (sizeof (JNIEnv));
2264 if (env == NULL)
2265 return JNI_ERR;
2266 env->p = &_Jv_JNIFunctions;
2267 env->ex = NULL;
2268 env->klass = NULL;
2269 env->locals
2270 = (_Jv_JNI_LocalFrame *) _Jv_MallocUnchecked (sizeof (_Jv_JNI_LocalFrame)
2271 + (FRAME_SIZE
2272 * sizeof (jobject)));
2273 if (env->locals == NULL)
2275 _Jv_Free (env);
2276 return JNI_ERR;
2279 env->locals->marker = MARK_SYSTEM;
2280 env->locals->size = FRAME_SIZE;
2281 env->locals->next = NULL;
2283 for (int i = 0; i < env->locals->size; ++i)
2284 env->locals->vec[i] = NULL;
2286 *penv = reinterpret_cast<void *> (env);
2288 // This thread might already be a Java thread -- this function might
2289 // have been called simply to set the new JNIEnv.
2290 if (_Jv_ThreadCurrent () == NULL)
2294 if (is_daemon)
2295 _Jv_AttachCurrentThreadAsDaemon (name, group);
2296 else
2297 _Jv_AttachCurrentThread (name, group);
2299 catch (jthrowable t)
2301 return JNI_ERR;
2304 _Jv_SetCurrentJNIEnv (env);
2306 return 0;
2309 // This is the one actually used by JNI.
2310 static jint JNICALL
2311 _Jv_JNI_AttachCurrentThread (JavaVM *vm, void **penv, void *args)
2313 return _Jv_JNI_AttachCurrentThread (vm, NULL, penv, args, false);
2316 static jint JNICALL
2317 _Jv_JNI_AttachCurrentThreadAsDaemon (JavaVM *vm, void **penv,
2318 void *args)
2320 return _Jv_JNI_AttachCurrentThread (vm, NULL, penv, args, true);
2323 static jint JNICALL
2324 _Jv_JNI_DestroyJavaVM (JavaVM *vm)
2326 JvAssert (the_vm && vm == the_vm);
2328 JNIEnv *env;
2329 if (_Jv_ThreadCurrent () != NULL)
2331 jstring main_name;
2332 // This sucks.
2335 main_name = JvNewStringLatin1 ("main");
2337 catch (jthrowable t)
2339 return JNI_ERR;
2342 jint r = _Jv_JNI_AttachCurrentThread (vm, main_name,
2343 reinterpret_cast<void **> (&env),
2344 NULL, false);
2345 if (r < 0)
2346 return r;
2348 else
2349 env = _Jv_GetCurrentJNIEnv ();
2351 _Jv_ThreadWait ();
2353 // Docs say that this always returns an error code.
2354 return JNI_ERR;
2357 jint JNICALL
2358 _Jv_JNI_DetachCurrentThread (JavaVM *)
2360 jint code = _Jv_DetachCurrentThread ();
2361 return code ? JNI_EDETACHED : 0;
2364 static jint JNICALL
2365 _Jv_JNI_GetEnv (JavaVM *, void **penv, jint version)
2367 if (_Jv_ThreadCurrent () == NULL)
2369 *penv = NULL;
2370 return JNI_EDETACHED;
2373 #ifdef ENABLE_JVMPI
2374 // Handle JVMPI requests.
2375 if (version == JVMPI_VERSION_1)
2377 *penv = (void *) &_Jv_JVMPI_Interface;
2378 return 0;
2380 #endif
2382 // FIXME: do we really want to support 1.1?
2383 if (version != JNI_VERSION_1_4 && version != JNI_VERSION_1_2
2384 && version != JNI_VERSION_1_1)
2386 *penv = NULL;
2387 return JNI_EVERSION;
2390 *penv = (void *) _Jv_GetCurrentJNIEnv ();
2391 return 0;
2394 jint JNICALL
2395 JNI_GetDefaultJavaVMInitArgs (void *args)
2397 jint version = * (jint *) args;
2398 // Here we only support 1.2 and 1.4.
2399 if (version != JNI_VERSION_1_2 && version != JNI_VERSION_1_4)
2400 return JNI_EVERSION;
2402 JavaVMInitArgs *ia = reinterpret_cast<JavaVMInitArgs *> (args);
2403 ia->version = JNI_VERSION_1_4;
2404 ia->nOptions = 0;
2405 ia->options = NULL;
2406 ia->ignoreUnrecognized = true;
2408 return 0;
2411 jint JNICALL
2412 JNI_CreateJavaVM (JavaVM **vm, void **penv, void *args)
2414 JvAssert (! the_vm);
2416 _Jv_CreateJavaVM (NULL);
2418 // FIXME: synchronize
2419 JavaVM *nvm = (JavaVM *) _Jv_MallocUnchecked (sizeof (JavaVM));
2420 if (nvm == NULL)
2421 return JNI_ERR;
2422 nvm->functions = &_Jv_JNI_InvokeFunctions;
2424 // Parse the arguments.
2425 if (args != NULL)
2427 jint version = * (jint *) args;
2428 // We only support 1.2 and 1.4.
2429 if (version != JNI_VERSION_1_2 && version != JNI_VERSION_1_4)
2430 return JNI_EVERSION;
2431 JavaVMInitArgs *ia = reinterpret_cast<JavaVMInitArgs *> (args);
2432 for (int i = 0; i < ia->nOptions; ++i)
2434 if (! strcmp (ia->options[i].optionString, "vfprintf")
2435 || ! strcmp (ia->options[i].optionString, "exit")
2436 || ! strcmp (ia->options[i].optionString, "abort"))
2438 // We are required to recognize these, but for now we
2439 // don't handle them in any way. FIXME.
2440 continue;
2442 else if (! strncmp (ia->options[i].optionString,
2443 "-verbose", sizeof ("-verbose") - 1))
2445 // We don't do anything with this option either. We
2446 // might want to make sure the argument is valid, but we
2447 // don't really care all that much for now.
2448 continue;
2450 else if (! strncmp (ia->options[i].optionString, "-D", 2))
2452 // FIXME.
2453 continue;
2455 else if (ia->ignoreUnrecognized)
2457 if (ia->options[i].optionString[0] == '_'
2458 || ! strncmp (ia->options[i].optionString, "-X", 2))
2459 continue;
2462 return JNI_ERR;
2466 jint r =_Jv_JNI_AttachCurrentThread (nvm, penv, NULL);
2467 if (r < 0)
2468 return r;
2470 the_vm = nvm;
2471 *vm = the_vm;
2473 return 0;
2476 jint JNICALL
2477 JNI_GetCreatedJavaVMs (JavaVM **vm_buffer, jsize buf_len, jsize *n_vms)
2479 if (buf_len <= 0)
2480 return JNI_ERR;
2482 // We only support a single VM.
2483 if (the_vm != NULL)
2485 vm_buffer[0] = the_vm;
2486 *n_vms = 1;
2488 else
2489 *n_vms = 0;
2490 return 0;
2493 JavaVM *
2494 _Jv_GetJavaVM ()
2496 // FIXME: synchronize
2497 if (! the_vm)
2499 JavaVM *nvm = (JavaVM *) _Jv_MallocUnchecked (sizeof (JavaVM));
2500 if (nvm != NULL)
2501 nvm->functions = &_Jv_JNI_InvokeFunctions;
2502 the_vm = nvm;
2505 // If this is a Java thread, we want to make sure it has an
2506 // associated JNIEnv.
2507 if (_Jv_ThreadCurrent () != NULL)
2509 void *ignore;
2510 _Jv_JNI_AttachCurrentThread (the_vm, &ignore, NULL);
2513 return the_vm;
2516 static jint JNICALL
2517 _Jv_JNI_GetJavaVM (JNIEnv *, JavaVM **vm)
2519 *vm = _Jv_GetJavaVM ();
2520 return *vm == NULL ? JNI_ERR : JNI_OK;
2525 #define RESERVED NULL
2527 struct JNINativeInterface _Jv_JNIFunctions =
2529 RESERVED,
2530 RESERVED,
2531 RESERVED,
2532 RESERVED,
2533 _Jv_JNI_GetVersion, // GetVersion
2534 _Jv_JNI_DefineClass, // DefineClass
2535 _Jv_JNI_FindClass, // FindClass
2536 _Jv_JNI_FromReflectedMethod, // FromReflectedMethod
2537 _Jv_JNI_FromReflectedField, // FromReflectedField
2538 _Jv_JNI_ToReflectedMethod, // ToReflectedMethod
2539 _Jv_JNI_GetSuperclass, // GetSuperclass
2540 _Jv_JNI_IsAssignableFrom, // IsAssignableFrom
2541 _Jv_JNI_ToReflectedField, // ToReflectedField
2542 _Jv_JNI_Throw, // Throw
2543 _Jv_JNI_ThrowNew, // ThrowNew
2544 _Jv_JNI_ExceptionOccurred, // ExceptionOccurred
2545 _Jv_JNI_ExceptionDescribe, // ExceptionDescribe
2546 _Jv_JNI_ExceptionClear, // ExceptionClear
2547 _Jv_JNI_FatalError, // FatalError
2549 _Jv_JNI_PushLocalFrame, // PushLocalFrame
2550 _Jv_JNI_PopLocalFrame, // PopLocalFrame
2551 _Jv_JNI_NewGlobalRef, // NewGlobalRef
2552 _Jv_JNI_DeleteGlobalRef, // DeleteGlobalRef
2553 _Jv_JNI_DeleteLocalRef, // DeleteLocalRef
2555 _Jv_JNI_IsSameObject, // IsSameObject
2557 _Jv_JNI_NewLocalRef, // NewLocalRef
2558 _Jv_JNI_EnsureLocalCapacity, // EnsureLocalCapacity
2560 _Jv_JNI_AllocObject, // AllocObject
2561 _Jv_JNI_NewObject, // NewObject
2562 _Jv_JNI_NewObjectV, // NewObjectV
2563 _Jv_JNI_NewObjectA, // NewObjectA
2564 _Jv_JNI_GetObjectClass, // GetObjectClass
2565 _Jv_JNI_IsInstanceOf, // IsInstanceOf
2566 _Jv_JNI_GetAnyMethodID<false>, // GetMethodID
2568 _Jv_JNI_CallMethod<jobject>, // CallObjectMethod
2569 _Jv_JNI_CallMethodV<jobject>, // CallObjectMethodV
2570 _Jv_JNI_CallMethodA<jobject>, // CallObjectMethodA
2571 _Jv_JNI_CallMethod<jboolean>, // CallBooleanMethod
2572 _Jv_JNI_CallMethodV<jboolean>, // CallBooleanMethodV
2573 _Jv_JNI_CallMethodA<jboolean>, // CallBooleanMethodA
2574 _Jv_JNI_CallMethod<jbyte>, // CallByteMethod
2575 _Jv_JNI_CallMethodV<jbyte>, // CallByteMethodV
2576 _Jv_JNI_CallMethodA<jbyte>, // CallByteMethodA
2577 _Jv_JNI_CallMethod<jchar>, // CallCharMethod
2578 _Jv_JNI_CallMethodV<jchar>, // CallCharMethodV
2579 _Jv_JNI_CallMethodA<jchar>, // CallCharMethodA
2580 _Jv_JNI_CallMethod<jshort>, // CallShortMethod
2581 _Jv_JNI_CallMethodV<jshort>, // CallShortMethodV
2582 _Jv_JNI_CallMethodA<jshort>, // CallShortMethodA
2583 _Jv_JNI_CallMethod<jint>, // CallIntMethod
2584 _Jv_JNI_CallMethodV<jint>, // CallIntMethodV
2585 _Jv_JNI_CallMethodA<jint>, // CallIntMethodA
2586 _Jv_JNI_CallMethod<jlong>, // CallLongMethod
2587 _Jv_JNI_CallMethodV<jlong>, // CallLongMethodV
2588 _Jv_JNI_CallMethodA<jlong>, // CallLongMethodA
2589 _Jv_JNI_CallMethod<jfloat>, // CallFloatMethod
2590 _Jv_JNI_CallMethodV<jfloat>, // CallFloatMethodV
2591 _Jv_JNI_CallMethodA<jfloat>, // CallFloatMethodA
2592 _Jv_JNI_CallMethod<jdouble>, // CallDoubleMethod
2593 _Jv_JNI_CallMethodV<jdouble>, // CallDoubleMethodV
2594 _Jv_JNI_CallMethodA<jdouble>, // CallDoubleMethodA
2595 _Jv_JNI_CallVoidMethod, // CallVoidMethod
2596 _Jv_JNI_CallVoidMethodV, // CallVoidMethodV
2597 _Jv_JNI_CallVoidMethodA, // CallVoidMethodA
2599 // Nonvirtual method invocation functions follow.
2600 _Jv_JNI_CallAnyMethod<jobject, nonvirtual>, // CallNonvirtualObjectMethod
2601 _Jv_JNI_CallAnyMethodV<jobject, nonvirtual>, // CallNonvirtualObjectMethodV
2602 _Jv_JNI_CallAnyMethodA<jobject, nonvirtual>, // CallNonvirtualObjectMethodA
2603 _Jv_JNI_CallAnyMethod<jboolean, nonvirtual>, // CallNonvirtualBooleanMethod
2604 _Jv_JNI_CallAnyMethodV<jboolean, nonvirtual>, // CallNonvirtualBooleanMethodV
2605 _Jv_JNI_CallAnyMethodA<jboolean, nonvirtual>, // CallNonvirtualBooleanMethodA
2606 _Jv_JNI_CallAnyMethod<jbyte, nonvirtual>, // CallNonvirtualByteMethod
2607 _Jv_JNI_CallAnyMethodV<jbyte, nonvirtual>, // CallNonvirtualByteMethodV
2608 _Jv_JNI_CallAnyMethodA<jbyte, nonvirtual>, // CallNonvirtualByteMethodA
2609 _Jv_JNI_CallAnyMethod<jchar, nonvirtual>, // CallNonvirtualCharMethod
2610 _Jv_JNI_CallAnyMethodV<jchar, nonvirtual>, // CallNonvirtualCharMethodV
2611 _Jv_JNI_CallAnyMethodA<jchar, nonvirtual>, // CallNonvirtualCharMethodA
2612 _Jv_JNI_CallAnyMethod<jshort, nonvirtual>, // CallNonvirtualShortMethod
2613 _Jv_JNI_CallAnyMethodV<jshort, nonvirtual>, // CallNonvirtualShortMethodV
2614 _Jv_JNI_CallAnyMethodA<jshort, nonvirtual>, // CallNonvirtualShortMethodA
2615 _Jv_JNI_CallAnyMethod<jint, nonvirtual>, // CallNonvirtualIntMethod
2616 _Jv_JNI_CallAnyMethodV<jint, nonvirtual>, // CallNonvirtualIntMethodV
2617 _Jv_JNI_CallAnyMethodA<jint, nonvirtual>, // CallNonvirtualIntMethodA
2618 _Jv_JNI_CallAnyMethod<jlong, nonvirtual>, // CallNonvirtualLongMethod
2619 _Jv_JNI_CallAnyMethodV<jlong, nonvirtual>, // CallNonvirtualLongMethodV
2620 _Jv_JNI_CallAnyMethodA<jlong, nonvirtual>, // CallNonvirtualLongMethodA
2621 _Jv_JNI_CallAnyMethod<jfloat, nonvirtual>, // CallNonvirtualFloatMethod
2622 _Jv_JNI_CallAnyMethodV<jfloat, nonvirtual>, // CallNonvirtualFloatMethodV
2623 _Jv_JNI_CallAnyMethodA<jfloat, nonvirtual>, // CallNonvirtualFloatMethodA
2624 _Jv_JNI_CallAnyMethod<jdouble, nonvirtual>, // CallNonvirtualDoubleMethod
2625 _Jv_JNI_CallAnyMethodV<jdouble, nonvirtual>, // CallNonvirtualDoubleMethodV
2626 _Jv_JNI_CallAnyMethodA<jdouble, nonvirtual>, // CallNonvirtualDoubleMethodA
2627 _Jv_JNI_CallAnyVoidMethod<nonvirtual>, // CallNonvirtualVoidMethod
2628 _Jv_JNI_CallAnyVoidMethodV<nonvirtual>, // CallNonvirtualVoidMethodV
2629 _Jv_JNI_CallAnyVoidMethodA<nonvirtual>, // CallNonvirtualVoidMethodA
2631 _Jv_JNI_GetAnyFieldID<false>, // GetFieldID
2632 _Jv_JNI_GetField<jobject>, // GetObjectField
2633 _Jv_JNI_GetField<jboolean>, // GetBooleanField
2634 _Jv_JNI_GetField<jbyte>, // GetByteField
2635 _Jv_JNI_GetField<jchar>, // GetCharField
2636 _Jv_JNI_GetField<jshort>, // GetShortField
2637 _Jv_JNI_GetField<jint>, // GetIntField
2638 _Jv_JNI_GetField<jlong>, // GetLongField
2639 _Jv_JNI_GetField<jfloat>, // GetFloatField
2640 _Jv_JNI_GetField<jdouble>, // GetDoubleField
2641 _Jv_JNI_SetField, // SetObjectField
2642 _Jv_JNI_SetField, // SetBooleanField
2643 _Jv_JNI_SetField, // SetByteField
2644 _Jv_JNI_SetField, // SetCharField
2645 _Jv_JNI_SetField, // SetShortField
2646 _Jv_JNI_SetField, // SetIntField
2647 _Jv_JNI_SetField, // SetLongField
2648 _Jv_JNI_SetField, // SetFloatField
2649 _Jv_JNI_SetField, // SetDoubleField
2650 _Jv_JNI_GetAnyMethodID<true>, // GetStaticMethodID
2652 _Jv_JNI_CallStaticMethod<jobject>, // CallStaticObjectMethod
2653 _Jv_JNI_CallStaticMethodV<jobject>, // CallStaticObjectMethodV
2654 _Jv_JNI_CallStaticMethodA<jobject>, // CallStaticObjectMethodA
2655 _Jv_JNI_CallStaticMethod<jboolean>, // CallStaticBooleanMethod
2656 _Jv_JNI_CallStaticMethodV<jboolean>, // CallStaticBooleanMethodV
2657 _Jv_JNI_CallStaticMethodA<jboolean>, // CallStaticBooleanMethodA
2658 _Jv_JNI_CallStaticMethod<jbyte>, // CallStaticByteMethod
2659 _Jv_JNI_CallStaticMethodV<jbyte>, // CallStaticByteMethodV
2660 _Jv_JNI_CallStaticMethodA<jbyte>, // CallStaticByteMethodA
2661 _Jv_JNI_CallStaticMethod<jchar>, // CallStaticCharMethod
2662 _Jv_JNI_CallStaticMethodV<jchar>, // CallStaticCharMethodV
2663 _Jv_JNI_CallStaticMethodA<jchar>, // CallStaticCharMethodA
2664 _Jv_JNI_CallStaticMethod<jshort>, // CallStaticShortMethod
2665 _Jv_JNI_CallStaticMethodV<jshort>, // CallStaticShortMethodV
2666 _Jv_JNI_CallStaticMethodA<jshort>, // CallStaticShortMethodA
2667 _Jv_JNI_CallStaticMethod<jint>, // CallStaticIntMethod
2668 _Jv_JNI_CallStaticMethodV<jint>, // CallStaticIntMethodV
2669 _Jv_JNI_CallStaticMethodA<jint>, // CallStaticIntMethodA
2670 _Jv_JNI_CallStaticMethod<jlong>, // CallStaticLongMethod
2671 _Jv_JNI_CallStaticMethodV<jlong>, // CallStaticLongMethodV
2672 _Jv_JNI_CallStaticMethodA<jlong>, // CallStaticLongMethodA
2673 _Jv_JNI_CallStaticMethod<jfloat>, // CallStaticFloatMethod
2674 _Jv_JNI_CallStaticMethodV<jfloat>, // CallStaticFloatMethodV
2675 _Jv_JNI_CallStaticMethodA<jfloat>, // CallStaticFloatMethodA
2676 _Jv_JNI_CallStaticMethod<jdouble>, // CallStaticDoubleMethod
2677 _Jv_JNI_CallStaticMethodV<jdouble>, // CallStaticDoubleMethodV
2678 _Jv_JNI_CallStaticMethodA<jdouble>, // CallStaticDoubleMethodA
2679 _Jv_JNI_CallStaticVoidMethod, // CallStaticVoidMethod
2680 _Jv_JNI_CallStaticVoidMethodV, // CallStaticVoidMethodV
2681 _Jv_JNI_CallStaticVoidMethodA, // CallStaticVoidMethodA
2683 _Jv_JNI_GetAnyFieldID<true>, // GetStaticFieldID
2684 _Jv_JNI_GetStaticField<jobject>, // GetStaticObjectField
2685 _Jv_JNI_GetStaticField<jboolean>, // GetStaticBooleanField
2686 _Jv_JNI_GetStaticField<jbyte>, // GetStaticByteField
2687 _Jv_JNI_GetStaticField<jchar>, // GetStaticCharField
2688 _Jv_JNI_GetStaticField<jshort>, // GetStaticShortField
2689 _Jv_JNI_GetStaticField<jint>, // GetStaticIntField
2690 _Jv_JNI_GetStaticField<jlong>, // GetStaticLongField
2691 _Jv_JNI_GetStaticField<jfloat>, // GetStaticFloatField
2692 _Jv_JNI_GetStaticField<jdouble>, // GetStaticDoubleField
2693 _Jv_JNI_SetStaticField, // SetStaticObjectField
2694 _Jv_JNI_SetStaticField, // SetStaticBooleanField
2695 _Jv_JNI_SetStaticField, // SetStaticByteField
2696 _Jv_JNI_SetStaticField, // SetStaticCharField
2697 _Jv_JNI_SetStaticField, // SetStaticShortField
2698 _Jv_JNI_SetStaticField, // SetStaticIntField
2699 _Jv_JNI_SetStaticField, // SetStaticLongField
2700 _Jv_JNI_SetStaticField, // SetStaticFloatField
2701 _Jv_JNI_SetStaticField, // SetStaticDoubleField
2702 _Jv_JNI_NewString, // NewString
2703 _Jv_JNI_GetStringLength, // GetStringLength
2704 _Jv_JNI_GetStringChars, // GetStringChars
2705 _Jv_JNI_ReleaseStringChars, // ReleaseStringChars
2706 _Jv_JNI_NewStringUTF, // NewStringUTF
2707 _Jv_JNI_GetStringUTFLength, // GetStringUTFLength
2708 _Jv_JNI_GetStringUTFChars, // GetStringUTFChars
2709 _Jv_JNI_ReleaseStringUTFChars, // ReleaseStringUTFChars
2710 _Jv_JNI_GetArrayLength, // GetArrayLength
2711 _Jv_JNI_NewObjectArray, // NewObjectArray
2712 _Jv_JNI_GetObjectArrayElement, // GetObjectArrayElement
2713 _Jv_JNI_SetObjectArrayElement, // SetObjectArrayElement
2714 _Jv_JNI_NewPrimitiveArray<jboolean, JvPrimClass (boolean)>,
2715 // NewBooleanArray
2716 _Jv_JNI_NewPrimitiveArray<jbyte, JvPrimClass (byte)>, // NewByteArray
2717 _Jv_JNI_NewPrimitiveArray<jchar, JvPrimClass (char)>, // NewCharArray
2718 _Jv_JNI_NewPrimitiveArray<jshort, JvPrimClass (short)>, // NewShortArray
2719 _Jv_JNI_NewPrimitiveArray<jint, JvPrimClass (int)>, // NewIntArray
2720 _Jv_JNI_NewPrimitiveArray<jlong, JvPrimClass (long)>, // NewLongArray
2721 _Jv_JNI_NewPrimitiveArray<jfloat, JvPrimClass (float)>, // NewFloatArray
2722 _Jv_JNI_NewPrimitiveArray<jdouble, JvPrimClass (double)>, // NewDoubleArray
2723 _Jv_JNI_GetPrimitiveArrayElements<jboolean, JvPrimClass (boolean)>,
2724 // GetBooleanArrayElements
2725 _Jv_JNI_GetPrimitiveArrayElements<jbyte, JvPrimClass (byte)>,
2726 // GetByteArrayElements
2727 _Jv_JNI_GetPrimitiveArrayElements<jchar, JvPrimClass (char)>,
2728 // GetCharArrayElements
2729 _Jv_JNI_GetPrimitiveArrayElements<jshort, JvPrimClass (short)>,
2730 // GetShortArrayElements
2731 _Jv_JNI_GetPrimitiveArrayElements<jint, JvPrimClass (int)>,
2732 // GetIntArrayElements
2733 _Jv_JNI_GetPrimitiveArrayElements<jlong, JvPrimClass (long)>,
2734 // GetLongArrayElements
2735 _Jv_JNI_GetPrimitiveArrayElements<jfloat, JvPrimClass (float)>,
2736 // GetFloatArrayElements
2737 _Jv_JNI_GetPrimitiveArrayElements<jdouble, JvPrimClass (double)>,
2738 // GetDoubleArrayElements
2739 _Jv_JNI_ReleasePrimitiveArrayElements<jboolean, JvPrimClass (boolean)>,
2740 // ReleaseBooleanArrayElements
2741 _Jv_JNI_ReleasePrimitiveArrayElements<jbyte, JvPrimClass (byte)>,
2742 // ReleaseByteArrayElements
2743 _Jv_JNI_ReleasePrimitiveArrayElements<jchar, JvPrimClass (char)>,
2744 // ReleaseCharArrayElements
2745 _Jv_JNI_ReleasePrimitiveArrayElements<jshort, JvPrimClass (short)>,
2746 // ReleaseShortArrayElements
2747 _Jv_JNI_ReleasePrimitiveArrayElements<jint, JvPrimClass (int)>,
2748 // ReleaseIntArrayElements
2749 _Jv_JNI_ReleasePrimitiveArrayElements<jlong, JvPrimClass (long)>,
2750 // ReleaseLongArrayElements
2751 _Jv_JNI_ReleasePrimitiveArrayElements<jfloat, JvPrimClass (float)>,
2752 // ReleaseFloatArrayElements
2753 _Jv_JNI_ReleasePrimitiveArrayElements<jdouble, JvPrimClass (double)>,
2754 // ReleaseDoubleArrayElements
2755 _Jv_JNI_GetPrimitiveArrayRegion<jboolean, JvPrimClass (boolean)>,
2756 // GetBooleanArrayRegion
2757 _Jv_JNI_GetPrimitiveArrayRegion<jbyte, JvPrimClass (byte)>,
2758 // GetByteArrayRegion
2759 _Jv_JNI_GetPrimitiveArrayRegion<jchar, JvPrimClass (char)>,
2760 // GetCharArrayRegion
2761 _Jv_JNI_GetPrimitiveArrayRegion<jshort, JvPrimClass (short)>,
2762 // GetShortArrayRegion
2763 _Jv_JNI_GetPrimitiveArrayRegion<jint, JvPrimClass (int)>,
2764 // GetIntArrayRegion
2765 _Jv_JNI_GetPrimitiveArrayRegion<jlong, JvPrimClass (long)>,
2766 // GetLongArrayRegion
2767 _Jv_JNI_GetPrimitiveArrayRegion<jfloat, JvPrimClass (float)>,
2768 // GetFloatArrayRegion
2769 _Jv_JNI_GetPrimitiveArrayRegion<jdouble, JvPrimClass (double)>,
2770 // GetDoubleArrayRegion
2771 _Jv_JNI_SetPrimitiveArrayRegion<jboolean, JvPrimClass (boolean)>,
2772 // SetBooleanArrayRegion
2773 _Jv_JNI_SetPrimitiveArrayRegion<jbyte, JvPrimClass (byte)>,
2774 // SetByteArrayRegion
2775 _Jv_JNI_SetPrimitiveArrayRegion<jchar, JvPrimClass (char)>,
2776 // SetCharArrayRegion
2777 _Jv_JNI_SetPrimitiveArrayRegion<jshort, JvPrimClass (short)>,
2778 // SetShortArrayRegion
2779 _Jv_JNI_SetPrimitiveArrayRegion<jint, JvPrimClass (int)>,
2780 // SetIntArrayRegion
2781 _Jv_JNI_SetPrimitiveArrayRegion<jlong, JvPrimClass (long)>,
2782 // SetLongArrayRegion
2783 _Jv_JNI_SetPrimitiveArrayRegion<jfloat, JvPrimClass (float)>,
2784 // SetFloatArrayRegion
2785 _Jv_JNI_SetPrimitiveArrayRegion<jdouble, JvPrimClass (double)>,
2786 // SetDoubleArrayRegion
2787 _Jv_JNI_RegisterNatives, // RegisterNatives
2788 _Jv_JNI_UnregisterNatives, // UnregisterNatives
2789 _Jv_JNI_MonitorEnter, // MonitorEnter
2790 _Jv_JNI_MonitorExit, // MonitorExit
2791 _Jv_JNI_GetJavaVM, // GetJavaVM
2793 _Jv_JNI_GetStringRegion, // GetStringRegion
2794 _Jv_JNI_GetStringUTFRegion, // GetStringUTFRegion
2795 _Jv_JNI_GetPrimitiveArrayCritical, // GetPrimitiveArrayCritical
2796 _Jv_JNI_ReleasePrimitiveArrayCritical, // ReleasePrimitiveArrayCritical
2797 _Jv_JNI_GetStringCritical, // GetStringCritical
2798 _Jv_JNI_ReleaseStringCritical, // ReleaseStringCritical
2800 _Jv_JNI_NewWeakGlobalRef, // NewWeakGlobalRef
2801 _Jv_JNI_DeleteWeakGlobalRef, // DeleteWeakGlobalRef
2803 _Jv_JNI_ExceptionCheck, // ExceptionCheck
2805 _Jv_JNI_NewDirectByteBuffer, // NewDirectByteBuffer
2806 _Jv_JNI_GetDirectBufferAddress, // GetDirectBufferAddress
2807 _Jv_JNI_GetDirectBufferCapacity // GetDirectBufferCapacity
2810 struct JNIInvokeInterface _Jv_JNI_InvokeFunctions =
2812 RESERVED,
2813 RESERVED,
2814 RESERVED,
2816 _Jv_JNI_DestroyJavaVM,
2817 _Jv_JNI_AttachCurrentThread,
2818 _Jv_JNI_DetachCurrentThread,
2819 _Jv_JNI_GetEnv,
2820 _Jv_JNI_AttachCurrentThreadAsDaemon