2003-09-04 Andreas Tobler <a.tobler@schweiz.ch>
[official-gcc.git] / libjava / jni.cc
blob49779078639253edf6d2381df737e097cf852fab
1 // jni.cc - JNI implementation, including the jump table.
3 /* Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003 Free Software Foundation
5 This file is part of libgcj.
7 This software is copyrighted work licensed under the terms of the
8 Libgcj License. Please consult the file "LIBGCJ_LICENSE" for
9 details. */
11 #include <config.h>
13 #include <stdio.h>
14 #include <stddef.h>
15 #include <string.h>
17 #include <gcj/cni.h>
18 #include <jvm.h>
19 #include <java-assert.h>
20 #include <jni.h>
21 #ifdef ENABLE_JVMPI
22 #include <jvmpi.h>
23 #endif
25 #include <java/lang/Class.h>
26 #include <java/lang/ClassLoader.h>
27 #include <java/lang/Throwable.h>
28 #include <java/lang/ArrayIndexOutOfBoundsException.h>
29 #include <java/lang/StringIndexOutOfBoundsException.h>
30 #include <java/lang/UnsatisfiedLinkError.h>
31 #include <java/lang/InstantiationException.h>
32 #include <java/lang/NoSuchFieldError.h>
33 #include <java/lang/NoSuchMethodError.h>
34 #include <java/lang/reflect/Constructor.h>
35 #include <java/lang/reflect/Method.h>
36 #include <java/lang/reflect/Modifier.h>
37 #include <java/lang/OutOfMemoryError.h>
38 #include <java/lang/Integer.h>
39 #include <java/lang/ThreadGroup.h>
40 #include <java/lang/Thread.h>
41 #include <java/lang/IllegalAccessError.h>
42 #include <java/nio/DirectByteBufferImpl.h>
43 #include <java/util/IdentityHashMap.h>
44 #include <gnu/gcj/RawData.h>
46 #include <gcj/method.h>
47 #include <gcj/field.h>
49 #include <java-interp.h>
50 #include <java-threads.h>
52 using namespace gcj;
54 // This enum is used to select different template instantiations in
55 // the invocation code.
56 enum invocation_type
58 normal,
59 nonvirtual,
60 static_type,
61 constructor
64 // Forward declarations.
65 extern struct JNINativeInterface _Jv_JNIFunctions;
66 extern struct JNIInvokeInterface _Jv_JNI_InvokeFunctions;
68 // Number of slots in the default frame. The VM must allow at least
69 // 16.
70 #define FRAME_SIZE 32
72 // Mark value indicating this is an overflow frame.
73 #define MARK_NONE 0
74 // Mark value indicating this is a user frame.
75 #define MARK_USER 1
76 // Mark value indicating this is a system frame.
77 #define MARK_SYSTEM 2
79 // This structure is used to keep track of local references.
80 struct _Jv_JNI_LocalFrame
82 // This is true if this frame object represents a pushed frame (eg
83 // from PushLocalFrame).
84 int marker : 2;
86 // Number of elements in frame.
87 int size : 30;
89 // Next frame in chain.
90 _Jv_JNI_LocalFrame *next;
92 // The elements. These are allocated using the C "struct hack".
93 jobject vec[0];
96 // This holds a reference count for all local references.
97 static java::util::IdentityHashMap *local_ref_table;
98 // This holds a reference count for all global references.
99 static java::util::IdentityHashMap *global_ref_table;
101 // The only VM.
102 static JavaVM *the_vm;
104 #ifdef ENABLE_JVMPI
105 // The only JVMPI interface description.
106 static JVMPI_Interface _Jv_JVMPI_Interface;
108 static jint
109 jvmpiEnableEvent (jint event_type, void *)
111 switch (event_type)
113 case JVMPI_EVENT_OBJECT_ALLOC:
114 _Jv_JVMPI_Notify_OBJECT_ALLOC = _Jv_JVMPI_Interface.NotifyEvent;
115 break;
117 case JVMPI_EVENT_THREAD_START:
118 _Jv_JVMPI_Notify_THREAD_START = _Jv_JVMPI_Interface.NotifyEvent;
119 break;
121 case JVMPI_EVENT_THREAD_END:
122 _Jv_JVMPI_Notify_THREAD_END = _Jv_JVMPI_Interface.NotifyEvent;
123 break;
125 default:
126 return JVMPI_NOT_AVAILABLE;
129 return JVMPI_SUCCESS;
132 static jint
133 jvmpiDisableEvent (jint event_type, void *)
135 switch (event_type)
137 case JVMPI_EVENT_OBJECT_ALLOC:
138 _Jv_JVMPI_Notify_OBJECT_ALLOC = NULL;
139 break;
141 default:
142 return JVMPI_NOT_AVAILABLE;
145 return JVMPI_SUCCESS;
147 #endif
151 void
152 _Jv_JNI_Init (void)
154 local_ref_table = new java::util::IdentityHashMap;
155 global_ref_table = new java::util::IdentityHashMap;
157 #ifdef ENABLE_JVMPI
158 _Jv_JVMPI_Interface.version = 1;
159 _Jv_JVMPI_Interface.EnableEvent = &jvmpiEnableEvent;
160 _Jv_JVMPI_Interface.DisableEvent = &jvmpiDisableEvent;
161 _Jv_JVMPI_Interface.EnableGC = &_Jv_EnableGC;
162 _Jv_JVMPI_Interface.DisableGC = &_Jv_DisableGC;
163 _Jv_JVMPI_Interface.RunGC = &_Jv_RunGC;
164 #endif
167 // Tell the GC that a certain pointer is live.
168 static void
169 mark_for_gc (jobject obj, java::util::IdentityHashMap *ref_table)
171 JvSynchronize sync (ref_table);
173 using namespace java::lang;
174 Integer *refcount = (Integer *) ref_table->get (obj);
175 jint val = (refcount == NULL) ? 0 : refcount->intValue ();
176 // FIXME: what about out of memory error?
177 ref_table->put (obj, new Integer (val + 1));
180 // Unmark a pointer.
181 static void
182 unmark_for_gc (jobject obj, java::util::IdentityHashMap *ref_table)
184 JvSynchronize sync (ref_table);
186 using namespace java::lang;
187 Integer *refcount = (Integer *) ref_table->get (obj);
188 JvAssert (refcount);
189 jint val = refcount->intValue () - 1;
190 JvAssert (val >= 0);
191 if (val == 0)
192 ref_table->remove (obj);
193 else
194 // FIXME: what about out of memory error?
195 ref_table->put (obj, new Integer (val));
198 // "Unwrap" some random non-reference type. This exists to simplify
199 // other template functions.
200 template<typename T>
201 static T
202 unwrap (T val)
204 return val;
207 // Unwrap a weak reference, if required.
208 template<typename T>
209 static T *
210 unwrap (T *obj)
212 using namespace gnu::gcj::runtime;
213 // We can compare the class directly because JNIWeakRef is `final'.
214 // Doing it this way is much faster.
215 if (obj == NULL || obj->getClass () != &JNIWeakRef::class$)
216 return obj;
217 JNIWeakRef *wr = reinterpret_cast<JNIWeakRef *> (obj);
218 return reinterpret_cast<T *> (wr->get ());
223 static jobject
224 (JNICALL _Jv_JNI_NewGlobalRef) (JNIEnv *, jobject obj)
226 // This seems weird but I think it is correct.
227 obj = unwrap (obj);
228 mark_for_gc (obj, global_ref_table);
229 return obj;
232 static void
233 (JNICALL _Jv_JNI_DeleteGlobalRef) (JNIEnv *, jobject obj)
235 // This seems weird but I think it is correct.
236 obj = unwrap (obj);
237 unmark_for_gc (obj, global_ref_table);
240 static void
241 (JNICALL _Jv_JNI_DeleteLocalRef) (JNIEnv *env, jobject obj)
243 _Jv_JNI_LocalFrame *frame;
245 // This seems weird but I think it is correct.
246 obj = unwrap (obj);
248 for (frame = env->locals; frame != NULL; frame = frame->next)
250 for (int i = 0; i < frame->size; ++i)
252 if (frame->vec[i] == obj)
254 frame->vec[i] = NULL;
255 unmark_for_gc (obj, local_ref_table);
256 return;
260 // Don't go past a marked frame.
261 JvAssert (frame->marker == MARK_NONE);
264 JvAssert (0);
267 static jint
268 (JNICALL _Jv_JNI_EnsureLocalCapacity) (JNIEnv *env, jint size)
270 // It is easier to just always allocate a new frame of the requested
271 // size. This isn't the most efficient thing, but for now we don't
272 // care. Note that _Jv_JNI_PushLocalFrame relies on this right now.
274 _Jv_JNI_LocalFrame *frame;
277 frame = (_Jv_JNI_LocalFrame *) _Jv_Malloc (sizeof (_Jv_JNI_LocalFrame)
278 + size * sizeof (jobject));
280 catch (jthrowable t)
282 env->ex = t;
283 return JNI_ERR;
286 frame->marker = MARK_NONE;
287 frame->size = size;
288 memset (&frame->vec[0], 0, size * sizeof (jobject));
289 frame->next = env->locals;
290 env->locals = frame;
292 return 0;
295 static jint
296 (JNICALL _Jv_JNI_PushLocalFrame) (JNIEnv *env, jint size)
298 jint r = _Jv_JNI_EnsureLocalCapacity (env, size);
299 if (r < 0)
300 return r;
302 // The new frame is on top.
303 env->locals->marker = MARK_USER;
305 return 0;
308 static jobject
309 (JNICALL _Jv_JNI_NewLocalRef) (JNIEnv *env, jobject obj)
311 // This seems weird but I think it is correct.
312 obj = unwrap (obj);
314 // Try to find an open slot somewhere in the topmost frame.
315 _Jv_JNI_LocalFrame *frame = env->locals;
316 bool done = false, set = false;
317 for (; frame != NULL && ! done; frame = frame->next)
319 for (int i = 0; i < frame->size; ++i)
321 if (frame->vec[i] == NULL)
323 set = true;
324 done = true;
325 frame->vec[i] = obj;
326 break;
330 // If we found a slot, or if the frame we just searched is the
331 // mark frame, then we are done.
332 if (done || frame == NULL || frame->marker != MARK_NONE)
333 break;
336 if (! set)
338 // No slots, so we allocate a new frame. According to the spec
339 // we could just die here. FIXME: return value.
340 _Jv_JNI_EnsureLocalCapacity (env, 16);
341 // We know the first element of the new frame will be ok.
342 env->locals->vec[0] = obj;
345 mark_for_gc (obj, local_ref_table);
346 return obj;
349 static jobject
350 (JNICALL _Jv_JNI_PopLocalFrame) (JNIEnv *env, jobject result, int stop)
352 _Jv_JNI_LocalFrame *rf = env->locals;
354 bool done = false;
355 while (rf != NULL && ! done)
357 for (int i = 0; i < rf->size; ++i)
358 if (rf->vec[i] != NULL)
359 unmark_for_gc (rf->vec[i], local_ref_table);
361 // If the frame we just freed is the marker frame, we are done.
362 done = (rf->marker == stop);
364 _Jv_JNI_LocalFrame *n = rf->next;
365 // When N==NULL, we've reached the stack-allocated frame, and we
366 // must not free it. However, we must be sure to clear all its
367 // elements, since we might conceivably reuse it.
368 if (n == NULL)
370 memset (&rf->vec[0], 0, rf->size * sizeof (jobject));
371 break;
374 _Jv_Free (rf);
375 rf = n;
378 // Update the local frame information.
379 env->locals = rf;
381 return result == NULL ? NULL : _Jv_JNI_NewLocalRef (env, result);
384 static jobject
385 (JNICALL _Jv_JNI_PopLocalFrame) (JNIEnv *env, jobject result)
387 return _Jv_JNI_PopLocalFrame (env, result, MARK_USER);
390 // Make sure an array's type is compatible with the type of the
391 // destination.
392 template<typename T>
393 static bool
394 _Jv_JNI_check_types (JNIEnv *env, JArray<T> *array, jclass K)
396 jclass klass = array->getClass()->getComponentType();
397 if (__builtin_expect (klass != K, false))
399 env->ex = new java::lang::IllegalAccessError ();
400 return false;
402 else
403 return true;
406 // Pop a `system' frame from the stack. This is `extern "C"' as it is
407 // used by the compiler.
408 extern "C" void
409 _Jv_JNI_PopSystemFrame (JNIEnv *env)
411 _Jv_JNI_PopLocalFrame (env, NULL, MARK_SYSTEM);
413 if (env->ex)
415 jthrowable t = env->ex;
416 env->ex = NULL;
417 throw t;
421 template<typename T> T extract_from_jvalue(jvalue const & t);
422 template<> jboolean extract_from_jvalue(jvalue const & jv) { return jv.z; }
423 template<> jbyte extract_from_jvalue(jvalue const & jv) { return jv.b; }
424 template<> jchar extract_from_jvalue(jvalue const & jv) { return jv.c; }
425 template<> jshort extract_from_jvalue(jvalue const & jv) { return jv.s; }
426 template<> jint extract_from_jvalue(jvalue const & jv) { return jv.i; }
427 template<> jlong extract_from_jvalue(jvalue const & jv) { return jv.j; }
428 template<> jfloat extract_from_jvalue(jvalue const & jv) { return jv.f; }
429 template<> jdouble extract_from_jvalue(jvalue const & jv) { return jv.d; }
430 template<> jobject extract_from_jvalue(jvalue const & jv) { return jv.l; }
433 // This function is used from other template functions. It wraps the
434 // return value appropriately; we specialize it so that object returns
435 // are turned into local references.
436 template<typename T>
437 static T
438 wrap_value (JNIEnv *, T value)
440 return value;
443 // This specialization is used for jobject, jclass, jstring, jarray,
444 // etc.
445 template<typename R, typename T>
446 static T *
447 wrap_value (JNIEnv *env, T *value)
449 return (value == NULL
450 ? value
451 : (T *) _Jv_JNI_NewLocalRef (env, (jobject) value));
456 static jint
457 (JNICALL _Jv_JNI_GetVersion) (JNIEnv *)
459 return JNI_VERSION_1_4;
462 static jclass
463 (JNICALL _Jv_JNI_DefineClass) (JNIEnv *env, const char *name, jobject loader,
464 const jbyte *buf, jsize bufLen)
468 loader = unwrap (loader);
470 jstring sname = JvNewStringUTF (name);
471 jbyteArray bytes = JvNewByteArray (bufLen);
473 jbyte *elts = elements (bytes);
474 memcpy (elts, buf, bufLen * sizeof (jbyte));
476 java::lang::ClassLoader *l
477 = reinterpret_cast<java::lang::ClassLoader *> (loader);
479 jclass result = l->defineClass (sname, bytes, 0, bufLen);
480 return (jclass) wrap_value (env, result);
482 catch (jthrowable t)
484 env->ex = t;
485 return NULL;
489 static jclass
490 (JNICALL _Jv_JNI_FindClass) (JNIEnv *env, const char *name)
492 // FIXME: assume that NAME isn't too long.
493 int len = strlen (name);
494 char s[len + 1];
495 for (int i = 0; i <= len; ++i)
496 s[i] = (name[i] == '/') ? '.' : name[i];
498 jclass r = NULL;
501 // This might throw an out of memory exception.
502 jstring n = JvNewStringUTF (s);
504 java::lang::ClassLoader *loader = NULL;
505 if (env->klass != NULL)
506 loader = env->klass->getClassLoaderInternal ();
508 if (loader == NULL)
510 // FIXME: should use getBaseClassLoader, but we don't have that
511 // yet.
512 loader = java::lang::ClassLoader::getSystemClassLoader ();
515 r = loader->loadClass (n);
517 catch (jthrowable t)
519 env->ex = t;
522 return (jclass) wrap_value (env, r);
525 static jclass
526 (JNICALL _Jv_JNI_GetSuperclass) (JNIEnv *env, jclass clazz)
528 return (jclass) wrap_value (env, unwrap (clazz)->getSuperclass ());
531 static jboolean
532 (JNICALL _Jv_JNI_IsAssignableFrom) (JNIEnv *, jclass clazz1, jclass clazz2)
534 return unwrap (clazz1)->isAssignableFrom (unwrap (clazz2));
537 static jint
538 (JNICALL _Jv_JNI_Throw) (JNIEnv *env, jthrowable obj)
540 // We check in case the user did some funky cast.
541 obj = unwrap (obj);
542 JvAssert (obj != NULL && java::lang::Throwable::class$.isInstance (obj));
543 env->ex = obj;
544 return 0;
547 static jint
548 (JNICALL _Jv_JNI_ThrowNew) (JNIEnv *env, jclass clazz, const char *message)
550 using namespace java::lang::reflect;
552 clazz = unwrap (clazz);
553 JvAssert (java::lang::Throwable::class$.isAssignableFrom (clazz));
555 int r = JNI_OK;
558 JArray<jclass> *argtypes
559 = (JArray<jclass> *) JvNewObjectArray (1, &java::lang::Class::class$,
560 NULL);
562 jclass *elts = elements (argtypes);
563 elts[0] = &StringClass;
565 Constructor *cons = clazz->getConstructor (argtypes);
567 jobjectArray values = JvNewObjectArray (1, &StringClass, NULL);
568 jobject *velts = elements (values);
569 velts[0] = JvNewStringUTF (message);
571 jobject obj = cons->newInstance (values);
573 env->ex = reinterpret_cast<jthrowable> (obj);
575 catch (jthrowable t)
577 env->ex = t;
578 r = JNI_ERR;
581 return r;
584 static jthrowable
585 (JNICALL _Jv_JNI_ExceptionOccurred) (JNIEnv *env)
587 return (jthrowable) wrap_value (env, env->ex);
590 static void
591 (JNICALL _Jv_JNI_ExceptionDescribe) (JNIEnv *env)
593 if (env->ex != NULL)
594 env->ex->printStackTrace();
597 static void
598 (JNICALL _Jv_JNI_ExceptionClear) (JNIEnv *env)
600 env->ex = NULL;
603 static jboolean
604 (JNICALL _Jv_JNI_ExceptionCheck) (JNIEnv *env)
606 return env->ex != NULL;
609 static void
610 (JNICALL _Jv_JNI_FatalError) (JNIEnv *, const char *message)
612 JvFail (message);
617 static jboolean
618 (JNICALL _Jv_JNI_IsSameObject) (JNIEnv *, jobject obj1, jobject obj2)
620 return unwrap (obj1) == unwrap (obj2);
623 static jobject
624 (JNICALL _Jv_JNI_AllocObject) (JNIEnv *env, jclass clazz)
626 jobject obj = NULL;
627 using namespace java::lang::reflect;
631 clazz = unwrap (clazz);
632 JvAssert (clazz && ! clazz->isArray ());
633 if (clazz->isInterface() || Modifier::isAbstract(clazz->getModifiers()))
634 env->ex = new java::lang::InstantiationException ();
635 else
636 obj = JvAllocObject (clazz);
638 catch (jthrowable t)
640 env->ex = t;
643 return wrap_value (env, obj);
646 static jclass
647 (JNICALL _Jv_JNI_GetObjectClass) (JNIEnv *env, jobject obj)
649 obj = unwrap (obj);
650 JvAssert (obj);
651 return (jclass) wrap_value (env, obj->getClass());
654 static jboolean
655 (JNICALL _Jv_JNI_IsInstanceOf) (JNIEnv *, jobject obj, jclass clazz)
657 return unwrap (clazz)->isInstance(unwrap (obj));
663 // This section concerns method invocation.
666 template<jboolean is_static>
667 static jmethodID
668 (JNICALL _Jv_JNI_GetAnyMethodID) (JNIEnv *env, jclass clazz,
669 const char *name, const char *sig)
673 clazz = unwrap (clazz);
674 _Jv_InitClass (clazz);
676 _Jv_Utf8Const *name_u = _Jv_makeUtf8Const ((char *) name, -1);
678 // FIXME: assume that SIG isn't too long.
679 int len = strlen (sig);
680 char s[len + 1];
681 for (int i = 0; i <= len; ++i)
682 s[i] = (sig[i] == '/') ? '.' : sig[i];
683 _Jv_Utf8Const *sig_u = _Jv_makeUtf8Const ((char *) s, -1);
685 JvAssert (! clazz->isPrimitive());
687 using namespace java::lang::reflect;
689 while (clazz != NULL)
691 jint count = JvNumMethods (clazz);
692 jmethodID meth = JvGetFirstMethod (clazz);
694 for (jint i = 0; i < count; ++i)
696 if (((is_static && Modifier::isStatic (meth->accflags))
697 || (! is_static && ! Modifier::isStatic (meth->accflags)))
698 && _Jv_equalUtf8Consts (meth->name, name_u)
699 && _Jv_equalUtf8Consts (meth->signature, sig_u))
700 return meth;
702 meth = meth->getNextMethod();
705 clazz = clazz->getSuperclass ();
708 env->ex = new java::lang::NoSuchMethodError ();
710 catch (jthrowable t)
712 env->ex = t;
715 return NULL;
718 // This is a helper function which turns a va_list into an array of
719 // `jvalue's. It needs signature information in order to do its work.
720 // The array of values must already be allocated.
721 static void
722 array_from_valist (jvalue *values, JArray<jclass> *arg_types, va_list vargs)
724 jclass *arg_elts = elements (arg_types);
725 for (int i = 0; i < arg_types->length; ++i)
727 // Here we assume that sizeof(int) >= sizeof(jint), because we
728 // use `int' when decoding the varargs. Likewise for
729 // float, and double. Also we assume that sizeof(jlong) >=
730 // sizeof(int), i.e. that jlong values are not further
731 // promoted.
732 JvAssert (sizeof (int) >= sizeof (jint));
733 JvAssert (sizeof (jlong) >= sizeof (int));
734 JvAssert (sizeof (double) >= sizeof (jfloat));
735 JvAssert (sizeof (double) >= sizeof (jdouble));
736 if (arg_elts[i] == JvPrimClass (byte))
737 values[i].b = (jbyte) va_arg (vargs, int);
738 else if (arg_elts[i] == JvPrimClass (short))
739 values[i].s = (jshort) va_arg (vargs, int);
740 else if (arg_elts[i] == JvPrimClass (int))
741 values[i].i = (jint) va_arg (vargs, int);
742 else if (arg_elts[i] == JvPrimClass (long))
743 values[i].j = (jlong) va_arg (vargs, jlong);
744 else if (arg_elts[i] == JvPrimClass (float))
745 values[i].f = (jfloat) va_arg (vargs, double);
746 else if (arg_elts[i] == JvPrimClass (double))
747 values[i].d = (jdouble) va_arg (vargs, double);
748 else if (arg_elts[i] == JvPrimClass (boolean))
749 values[i].z = (jboolean) va_arg (vargs, int);
750 else if (arg_elts[i] == JvPrimClass (char))
751 values[i].c = (jchar) va_arg (vargs, int);
752 else
754 // An object.
755 values[i].l = unwrap (va_arg (vargs, jobject));
760 // This can call any sort of method: virtual, "nonvirtual", static, or
761 // constructor.
762 template<typename T, invocation_type style>
763 static T
764 (JNICALL _Jv_JNI_CallAnyMethodV) (JNIEnv *env, jobject obj, jclass klass,
765 jmethodID id, va_list vargs)
767 obj = unwrap (obj);
768 klass = unwrap (klass);
770 if (style == normal)
771 id = _Jv_LookupDeclaredMethod (obj->getClass (), id->name, id->signature);
773 jclass decl_class = klass ? klass : obj->getClass ();
774 JvAssert (decl_class != NULL);
776 jclass return_type;
777 JArray<jclass> *arg_types;
781 _Jv_GetTypesFromSignature (id, decl_class,
782 &arg_types, &return_type);
784 jvalue args[arg_types->length];
785 array_from_valist (args, arg_types, vargs);
787 // For constructors we need to pass the Class we are instantiating.
788 if (style == constructor)
789 return_type = klass;
791 jvalue result;
792 _Jv_CallAnyMethodA (obj, return_type, id,
793 style == constructor,
794 arg_types, args, &result);
796 return wrap_value (env, extract_from_jvalue<T>(result));
798 catch (jthrowable t)
800 env->ex = t;
803 return wrap_value (env, (T) 0);
806 template<typename T, invocation_type style>
807 static T
808 (JNICALL _Jv_JNI_CallAnyMethod) (JNIEnv *env, jobject obj, jclass klass,
809 jmethodID method, ...)
811 va_list args;
812 T result;
814 va_start (args, method);
815 result = _Jv_JNI_CallAnyMethodV<T, style> (env, obj, klass, method, args);
816 va_end (args);
818 return result;
821 template<typename T, invocation_type style>
822 static T
823 (JNICALL _Jv_JNI_CallAnyMethodA) (JNIEnv *env, jobject obj, jclass klass,
824 jmethodID id, jvalue *args)
826 obj = unwrap (obj);
827 klass = unwrap (klass);
829 if (style == normal)
830 id = _Jv_LookupDeclaredMethod (obj->getClass (), id->name, id->signature);
832 jclass decl_class = klass ? klass : obj->getClass ();
833 JvAssert (decl_class != NULL);
835 jclass return_type;
836 JArray<jclass> *arg_types;
839 _Jv_GetTypesFromSignature (id, decl_class,
840 &arg_types, &return_type);
842 // For constructors we need to pass the Class we are instantiating.
843 if (style == constructor)
844 return_type = klass;
846 // Unwrap arguments as required. Eww.
847 jclass *type_elts = elements (arg_types);
848 jvalue arg_copy[arg_types->length];
849 for (int i = 0; i < arg_types->length; ++i)
851 if (type_elts[i]->isPrimitive ())
852 arg_copy[i] = args[i];
853 else
854 arg_copy[i].l = unwrap (args[i].l);
857 jvalue result;
858 _Jv_CallAnyMethodA (obj, return_type, id,
859 style == constructor,
860 arg_types, arg_copy, &result);
862 return wrap_value (env, extract_from_jvalue<T>(result));
864 catch (jthrowable t)
866 env->ex = t;
869 return wrap_value (env, (T) 0);
872 template<invocation_type style>
873 static void
874 (JNICALL _Jv_JNI_CallAnyVoidMethodV) (JNIEnv *env, jobject obj, jclass klass,
875 jmethodID id, va_list vargs)
877 obj = unwrap (obj);
878 klass = unwrap (klass);
880 if (style == normal)
881 id = _Jv_LookupDeclaredMethod (obj->getClass (), id->name, id->signature);
883 jclass decl_class = klass ? klass : obj->getClass ();
884 JvAssert (decl_class != NULL);
886 jclass return_type;
887 JArray<jclass> *arg_types;
890 _Jv_GetTypesFromSignature (id, decl_class,
891 &arg_types, &return_type);
893 jvalue args[arg_types->length];
894 array_from_valist (args, arg_types, vargs);
896 // For constructors we need to pass the Class we are instantiating.
897 if (style == constructor)
898 return_type = klass;
900 _Jv_CallAnyMethodA (obj, return_type, id,
901 style == constructor,
902 arg_types, args, NULL);
904 catch (jthrowable t)
906 env->ex = t;
910 template<invocation_type style>
911 static void
912 (JNICALL _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
924 (JNICALL _Jv_JNI_CallAnyVoidMethodA) (JNIEnv *env, jobject obj, jclass klass,
925 jmethodID id, jvalue *args)
927 if (style == normal)
928 id = _Jv_LookupDeclaredMethod (obj->getClass (), id->name, id->signature);
930 jclass decl_class = klass ? klass : obj->getClass ();
931 JvAssert (decl_class != NULL);
933 jclass return_type;
934 JArray<jclass> *arg_types;
937 _Jv_GetTypesFromSignature (id, decl_class,
938 &arg_types, &return_type);
940 // Unwrap arguments as required. Eww.
941 jclass *type_elts = elements (arg_types);
942 jvalue arg_copy[arg_types->length];
943 for (int i = 0; i < arg_types->length; ++i)
945 if (type_elts[i]->isPrimitive ())
946 arg_copy[i] = args[i];
947 else
948 arg_copy[i].l = unwrap (args[i].l);
951 _Jv_CallAnyMethodA (obj, return_type, id,
952 style == constructor,
953 arg_types, args, NULL);
955 catch (jthrowable t)
957 env->ex = t;
961 // Functions with this signature are used to implement functions in
962 // the CallMethod family.
963 template<typename T>
964 static T
965 (JNICALL _Jv_JNI_CallMethodV) (JNIEnv *env, jobject obj,
966 jmethodID id, va_list args)
968 return _Jv_JNI_CallAnyMethodV<T, normal> (env, obj, NULL, id, args);
971 // Functions with this signature are used to implement functions in
972 // the CallMethod family.
973 template<typename T>
974 static T
975 (JNICALL _Jv_JNI_CallMethod) (JNIEnv *env, jobject obj, jmethodID id, ...)
977 va_list args;
978 T result;
980 va_start (args, id);
981 result = _Jv_JNI_CallAnyMethodV<T, normal> (env, obj, NULL, id, args);
982 va_end (args);
984 return result;
987 // Functions with this signature are used to implement functions in
988 // the CallMethod family.
989 template<typename T>
990 static T
991 (JNICALL _Jv_JNI_CallMethodA) (JNIEnv *env, jobject obj,
992 jmethodID id, jvalue *args)
994 return _Jv_JNI_CallAnyMethodA<T, normal> (env, obj, NULL, id, args);
997 static void
998 (JNICALL _Jv_JNI_CallVoidMethodV) (JNIEnv *env, jobject obj,
999 jmethodID id, va_list args)
1001 _Jv_JNI_CallAnyVoidMethodV<normal> (env, obj, NULL, id, args);
1004 static void
1005 (JNICALL _Jv_JNI_CallVoidMethod) (JNIEnv *env, jobject obj, jmethodID id, ...)
1007 va_list args;
1009 va_start (args, id);
1010 _Jv_JNI_CallAnyVoidMethodV<normal> (env, obj, NULL, id, args);
1011 va_end (args);
1014 static void
1015 (JNICALL _Jv_JNI_CallVoidMethodA) (JNIEnv *env, jobject obj,
1016 jmethodID id, jvalue *args)
1018 _Jv_JNI_CallAnyVoidMethodA<normal> (env, obj, NULL, id, args);
1021 // Functions with this signature are used to implement functions in
1022 // the CallStaticMethod family.
1023 template<typename T>
1024 static T
1025 (JNICALL _Jv_JNI_CallStaticMethodV) (JNIEnv *env, jclass klass,
1026 jmethodID id, va_list args)
1028 JvAssert (((id->accflags) & java::lang::reflect::Modifier::STATIC));
1029 JvAssert (java::lang::Class::class$.isInstance (unwrap (klass)));
1031 return _Jv_JNI_CallAnyMethodV<T, static_type> (env, NULL, klass, id, args);
1034 // Functions with this signature are used to implement functions in
1035 // the CallStaticMethod family.
1036 template<typename T>
1037 static T
1038 (JNICALL _Jv_JNI_CallStaticMethod) (JNIEnv *env, jclass klass,
1039 jmethodID id, ...)
1041 va_list args;
1042 T result;
1044 JvAssert (((id->accflags) & java::lang::reflect::Modifier::STATIC));
1045 JvAssert (java::lang::Class::class$.isInstance (unwrap (klass)));
1047 va_start (args, id);
1048 result = _Jv_JNI_CallAnyMethodV<T, static_type> (env, NULL, klass,
1049 id, args);
1050 va_end (args);
1052 return result;
1055 // Functions with this signature are used to implement functions in
1056 // the CallStaticMethod family.
1057 template<typename T>
1058 static T
1059 (JNICALL _Jv_JNI_CallStaticMethodA) (JNIEnv *env, jclass klass, jmethodID id,
1060 jvalue *args)
1062 JvAssert (((id->accflags) & java::lang::reflect::Modifier::STATIC));
1063 JvAssert (java::lang::Class::class$.isInstance (unwrap (klass)));
1065 return _Jv_JNI_CallAnyMethodA<T, static_type> (env, NULL, klass, id, args);
1068 static void
1069 (JNICALL _Jv_JNI_CallStaticVoidMethodV) (JNIEnv *env, jclass klass,
1070 jmethodID id, va_list args)
1072 _Jv_JNI_CallAnyVoidMethodV<static_type> (env, NULL, klass, id, args);
1075 static void
1076 (JNICALL _Jv_JNI_CallStaticVoidMethod) (JNIEnv *env, jclass klass,
1077 jmethodID id, ...)
1079 va_list args;
1081 va_start (args, id);
1082 _Jv_JNI_CallAnyVoidMethodV<static_type> (env, NULL, klass, id, args);
1083 va_end (args);
1086 static void
1087 (JNICALL _Jv_JNI_CallStaticVoidMethodA) (JNIEnv *env, jclass klass,
1088 jmethodID id, jvalue *args)
1090 _Jv_JNI_CallAnyVoidMethodA<static_type> (env, NULL, klass, id, args);
1093 static jobject
1094 (JNICALL _Jv_JNI_NewObjectV) (JNIEnv *env, jclass klass,
1095 jmethodID id, va_list args)
1097 JvAssert (klass && ! klass->isArray ());
1098 JvAssert (! strcmp (id->name->data, "<init>")
1099 && id->signature->length > 2
1100 && id->signature->data[0] == '('
1101 && ! strcmp (&id->signature->data[id->signature->length - 2],
1102 ")V"));
1104 return _Jv_JNI_CallAnyMethodV<jobject, constructor> (env, NULL, klass,
1105 id, args);
1108 static jobject
1109 (JNICALL _Jv_JNI_NewObject) (JNIEnv *env, jclass klass, jmethodID id, ...)
1111 JvAssert (klass && ! klass->isArray ());
1112 JvAssert (! strcmp (id->name->data, "<init>")
1113 && id->signature->length > 2
1114 && id->signature->data[0] == '('
1115 && ! strcmp (&id->signature->data[id->signature->length - 2],
1116 ")V"));
1118 va_list args;
1119 jobject result;
1121 va_start (args, id);
1122 result = _Jv_JNI_CallAnyMethodV<jobject, constructor> (env, NULL, klass,
1123 id, args);
1124 va_end (args);
1126 return result;
1129 static jobject
1130 (JNICALL _Jv_JNI_NewObjectA) (JNIEnv *env, jclass klass, jmethodID id,
1131 jvalue *args)
1133 JvAssert (klass && ! klass->isArray ());
1134 JvAssert (! strcmp (id->name->data, "<init>")
1135 && id->signature->length > 2
1136 && id->signature->data[0] == '('
1137 && ! strcmp (&id->signature->data[id->signature->length - 2],
1138 ")V"));
1140 return _Jv_JNI_CallAnyMethodA<jobject, constructor> (env, NULL, klass,
1141 id, args);
1146 template<typename T>
1147 static T
1148 (JNICALL _Jv_JNI_GetField) (JNIEnv *env, jobject obj, jfieldID field)
1150 obj = unwrap (obj);
1151 JvAssert (obj);
1152 T *ptr = (T *) ((char *) obj + field->getOffset ());
1153 return wrap_value (env, *ptr);
1156 template<typename T>
1157 static void
1158 (JNICALL _Jv_JNI_SetField) (JNIEnv *, jobject obj, jfieldID field, T value)
1160 obj = unwrap (obj);
1161 value = unwrap (value);
1163 JvAssert (obj);
1164 T *ptr = (T *) ((char *) obj + field->getOffset ());
1165 *ptr = value;
1168 template<jboolean is_static>
1169 static jfieldID
1170 (JNICALL _Jv_JNI_GetAnyFieldID) (JNIEnv *env, jclass clazz,
1171 const char *name, const char *sig)
1175 clazz = unwrap (clazz);
1177 _Jv_InitClass (clazz);
1179 _Jv_Utf8Const *a_name = _Jv_makeUtf8Const ((char *) name, -1);
1181 // FIXME: assume that SIG isn't too long.
1182 int len = strlen (sig);
1183 char s[len + 1];
1184 for (int i = 0; i <= len; ++i)
1185 s[i] = (sig[i] == '/') ? '.' : sig[i];
1186 jclass field_class = _Jv_FindClassFromSignature ((char *) s, NULL);
1188 // FIXME: what if field_class == NULL?
1190 java::lang::ClassLoader *loader = clazz->getClassLoaderInternal ();
1191 while (clazz != NULL)
1193 // We acquire the class lock so that fields aren't resolved
1194 // while we are running.
1195 JvSynchronize sync (clazz);
1197 jint count = (is_static
1198 ? JvNumStaticFields (clazz)
1199 : JvNumInstanceFields (clazz));
1200 jfieldID field = (is_static
1201 ? JvGetFirstStaticField (clazz)
1202 : JvGetFirstInstanceField (clazz));
1203 for (jint i = 0; i < count; ++i)
1205 _Jv_Utf8Const *f_name = field->getNameUtf8Const(clazz);
1207 // The field might be resolved or it might not be. It
1208 // is much simpler to always resolve it.
1209 _Jv_ResolveField (field, loader);
1210 if (_Jv_equalUtf8Consts (f_name, a_name)
1211 && field->getClass() == field_class)
1212 return field;
1214 field = field->getNextField ();
1217 clazz = clazz->getSuperclass ();
1220 env->ex = new java::lang::NoSuchFieldError ();
1222 catch (jthrowable t)
1224 env->ex = t;
1226 return NULL;
1229 template<typename T>
1230 static T
1231 (JNICALL _Jv_JNI_GetStaticField) (JNIEnv *env, jclass, jfieldID field)
1233 T *ptr = (T *) field->u.addr;
1234 return wrap_value (env, *ptr);
1237 template<typename T>
1238 static void
1239 (JNICALL _Jv_JNI_SetStaticField) (JNIEnv *, jclass, jfieldID field, T value)
1241 value = unwrap (value);
1242 T *ptr = (T *) field->u.addr;
1243 *ptr = value;
1246 static jstring
1247 (JNICALL _Jv_JNI_NewString) (JNIEnv *env, const jchar *unichars, jsize len)
1251 jstring r = _Jv_NewString (unichars, len);
1252 return (jstring) wrap_value (env, r);
1254 catch (jthrowable t)
1256 env->ex = t;
1257 return NULL;
1261 static jsize
1262 (JNICALL _Jv_JNI_GetStringLength) (JNIEnv *, jstring string)
1264 return unwrap (string)->length();
1267 static const jchar *
1268 (JNICALL _Jv_JNI_GetStringChars) (JNIEnv *, jstring string, jboolean *isCopy)
1270 string = unwrap (string);
1271 jchar *result = _Jv_GetStringChars (string);
1272 mark_for_gc (string, global_ref_table);
1273 if (isCopy)
1274 *isCopy = false;
1275 return (const jchar *) result;
1278 static void
1279 (JNICALL _Jv_JNI_ReleaseStringChars) (JNIEnv *, jstring string, const jchar *)
1281 unmark_for_gc (unwrap (string), global_ref_table);
1284 static jstring
1285 (JNICALL _Jv_JNI_NewStringUTF) (JNIEnv *env, const char *bytes)
1289 jstring result = JvNewStringUTF (bytes);
1290 return (jstring) wrap_value (env, result);
1292 catch (jthrowable t)
1294 env->ex = t;
1295 return NULL;
1299 static jsize
1300 (JNICALL _Jv_JNI_GetStringUTFLength) (JNIEnv *, jstring string)
1302 return JvGetStringUTFLength (unwrap (string));
1305 static const char *
1306 (JNICALL _Jv_JNI_GetStringUTFChars) (JNIEnv *env, jstring string,
1307 jboolean *isCopy)
1309 string = unwrap (string);
1310 jsize len = JvGetStringUTFLength (string);
1313 char *r = (char *) _Jv_Malloc (len + 1);
1314 JvGetStringUTFRegion (string, 0, len, 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
1330 (JNICALL _Jv_JNI_ReleaseStringUTFChars) (JNIEnv *, jstring, const char *utf)
1332 _Jv_Free ((void *) utf);
1335 static void
1336 (JNICALL _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
1358 (JNICALL _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 *
1380 (JNICALL _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
1389 (JNICALL _Jv_JNI_ReleaseStringCritical) (JNIEnv *, jstring, const jchar *)
1391 // Nothing.
1394 static jsize
1395 (JNICALL _Jv_JNI_GetArrayLength) (JNIEnv *, jarray array)
1397 return unwrap (array)->length;
1400 static jarray
1401 (JNICALL _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 (jarray) wrap_value (env, result);
1413 catch (jthrowable t)
1415 env->ex = t;
1416 return NULL;
1420 static jobject
1421 (JNICALL _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
1431 (JNICALL _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> *
1453 (JNICALL _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 *
1468 (JNICALL _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
1486 (JNICALL _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
1499 (JNICALL _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
1531 (JNICALL _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 *
1560 (JNICALL _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
1574 (JNICALL _Jv_JNI_ReleasePrimitiveArrayCritical) (JNIEnv *, jarray, void *, jint)
1576 // Nothing.
1579 static jint
1580 (JNICALL _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
1595 (JNICALL _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
1611 (JNICALL _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
1632 (JNICALL _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
1642 (JNICALL _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
1677 (JNICALL _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
1689 (JNICALL _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
1710 (JNICALL _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
1723 (JNICALL _Jv_JNI_NewDirectByteBuffer) (JNIEnv *, void *address, jlong length)
1725 using namespace gnu::gcj;
1726 using namespace java::nio;
1727 return new DirectByteBufferImpl (reinterpret_cast<RawData *> (address),
1728 length);
1731 static void *
1732 (JNICALL _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
1740 (JNICALL _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
1864 (JNICALL _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->data, methods[j].name)
1885 && ! strcmp (self->signature->data, methods[j].signature))
1887 if (! (self->accflags
1888 & java::lang::reflect::Modifier::NATIVE))
1889 break;
1891 // Found a match that is native.
1892 found = true;
1893 nathash_add (&methods[j]);
1895 break;
1899 if (! found)
1901 jstring m = JvNewStringUTF (methods[j].name);
1904 env->ex =new java::lang::NoSuchMethodError (m);
1906 catch (jthrowable t)
1908 env->ex = t;
1910 return JNI_ERR;
1914 return JNI_OK;
1917 static jint
1918 (JNICALL _Jv_JNI_UnregisterNatives) (JNIEnv *, jclass)
1920 // FIXME -- we could implement this.
1921 return JNI_ERR;
1926 // Add a character to the buffer, encoding properly.
1927 static void
1928 add_char (char *buf, jchar c, int *here)
1930 if (c == '_')
1932 buf[(*here)++] = '_';
1933 buf[(*here)++] = '1';
1935 else if (c == ';')
1937 buf[(*here)++] = '_';
1938 buf[(*here)++] = '2';
1940 else if (c == '[')
1942 buf[(*here)++] = '_';
1943 buf[(*here)++] = '3';
1946 // Also check for `.' here because we might be passed an internal
1947 // qualified class name like `foo.bar'.
1948 else if (c == '/' || c == '.')
1949 buf[(*here)++] = '_';
1950 else if ((c >= '0' && c <= '9')
1951 || (c >= 'a' && c <= 'z')
1952 || (c >= 'A' && c <= 'Z'))
1953 buf[(*here)++] = (char) c;
1954 else
1956 // "Unicode" character.
1957 buf[(*here)++] = '_';
1958 buf[(*here)++] = '0';
1959 for (int i = 0; i < 4; ++i)
1961 int val = c & 0x0f;
1962 buf[(*here) + 3 - i] = (val > 10) ? ('a' + val - 10) : ('0' + val);
1963 c >>= 4;
1965 *here += 4;
1969 // Compute a mangled name for a native function. This computes the
1970 // long name, and also returns an index which indicates where a NUL
1971 // can be placed to create the short name. This function assumes that
1972 // the buffer is large enough for its results.
1973 static void
1974 mangled_name (jclass klass, _Jv_Utf8Const *func_name,
1975 _Jv_Utf8Const *signature, char *buf, int *long_start)
1977 strcpy (buf, "Java_");
1978 int here = 5;
1980 // Add fully qualified class name.
1981 jchar *chars = _Jv_GetStringChars (klass->getName ());
1982 jint len = klass->getName ()->length ();
1983 for (int i = 0; i < len; ++i)
1984 add_char (buf, chars[i], &here);
1986 // Don't use add_char because we need a literal `_'.
1987 buf[here++] = '_';
1989 const unsigned char *fn = (const unsigned char *) func_name->data;
1990 const unsigned char *limit = fn + func_name->length;
1991 for (int i = 0; ; ++i)
1993 int ch = UTF8_GET (fn, limit);
1994 if (ch < 0)
1995 break;
1996 add_char (buf, ch, &here);
1999 // This is where the long signature begins.
2000 *long_start = here;
2001 buf[here++] = '_';
2002 buf[here++] = '_';
2004 const unsigned char *sig = (const unsigned char *) signature->data;
2005 limit = sig + signature->length;
2006 JvAssert (sig[0] == '(');
2007 ++sig;
2008 while (1)
2010 int ch = UTF8_GET (sig, limit);
2011 if (ch == ')' || ch < 0)
2012 break;
2013 add_char (buf, ch, &here);
2016 buf[here] = '\0';
2019 // Return the current thread's JNIEnv; if one does not exist, create
2020 // it. Also create a new system frame for use. This is `extern "C"'
2021 // because the compiler calls it.
2022 extern "C" JNIEnv *
2023 _Jv_GetJNIEnvNewFrame (jclass klass)
2025 JNIEnv *env = _Jv_GetCurrentJNIEnv ();
2026 if (env == NULL)
2028 env = (JNIEnv *) _Jv_MallocUnchecked (sizeof (JNIEnv));
2029 env->p = &_Jv_JNIFunctions;
2030 env->klass = klass;
2031 env->locals = NULL;
2032 // We set env->ex below.
2034 _Jv_SetCurrentJNIEnv (env);
2037 _Jv_JNI_LocalFrame *frame
2038 = (_Jv_JNI_LocalFrame *) _Jv_MallocUnchecked (sizeof (_Jv_JNI_LocalFrame)
2039 + (FRAME_SIZE
2040 * sizeof (jobject)));
2042 frame->marker = MARK_SYSTEM;
2043 frame->size = FRAME_SIZE;
2044 frame->next = env->locals;
2046 for (int i = 0; i < frame->size; ++i)
2047 frame->vec[i] = NULL;
2049 env->locals = frame;
2050 env->ex = NULL;
2052 return env;
2055 // Return the function which implements a particular JNI method. If
2056 // we can't find the function, we throw the appropriate exception.
2057 // This is `extern "C"' because the compiler uses it.
2058 extern "C" void *
2059 _Jv_LookupJNIMethod (jclass klass, _Jv_Utf8Const *name,
2060 _Jv_Utf8Const *signature, int args_size)
2062 char buf[10 + 6 * (name->length + signature->length) + 12];
2063 int long_start;
2064 void *function;
2066 // Synchronize on something convenient. Right now we use the hash.
2067 JvSynchronize sync (global_ref_table);
2069 // First see if we have an override in the hash table.
2070 strncpy (buf, name->data, name->length);
2071 buf[name->length] = '\0';
2072 strncpy (buf + name->length + 1, signature->data, signature->length);
2073 buf[name->length + signature->length + 1] = '\0';
2074 JNINativeMethod meth;
2075 meth.name = buf;
2076 meth.signature = buf + name->length + 1;
2077 function = nathash_find (&meth);
2078 if (function != NULL)
2079 return function;
2081 // If there was no override, then look in the symbol table.
2082 buf[0] = '_';
2083 mangled_name (klass, name, signature, buf + 1, &long_start);
2084 char c = buf[long_start + 1];
2085 buf[long_start + 1] = '\0';
2087 function = _Jv_FindSymbolInExecutable (buf + 1);
2088 #ifdef WIN32
2089 // On Win32, we use the "stdcall" calling convention (see JNICALL
2090 // in jni.h).
2092 // For a function named 'fooBar' that takes 'nn' bytes as arguments,
2093 // by default, MinGW GCC exports it as 'fooBar@nn', MSVC exports it
2094 // as '_fooBar@nn' and Borland C exports it as 'fooBar'. We try to
2095 // take care of all these variations here.
2097 char asz_buf[12]; /* '@' + '2147483647' (32-bit INT_MAX) + '\0' */
2098 char long_nm_sv[11]; /* Ditto, except for the '\0'. */
2100 if (function == NULL)
2102 // We have tried searching for the 'fooBar' form (BCC) - now
2103 // try the others.
2105 // First, save the part of the long name that will be damaged
2106 // by appending '@nn'.
2107 memcpy (long_nm_sv, (buf + long_start + 1 + 1), sizeof (long_nm_sv));
2109 sprintf (asz_buf, "@%d", args_size);
2110 strcat (buf, asz_buf);
2112 // Search for the '_fooBar@nn' form (MSVC).
2113 function = _Jv_FindSymbolInExecutable (buf);
2115 if (function == NULL)
2117 // Search for the 'fooBar@nn' form (MinGW GCC).
2118 function = _Jv_FindSymbolInExecutable (buf + 1);
2121 #else /* WIN32 */
2122 args_size; /* Dummy statement to avoid unused parameter warning */
2123 #endif /* ! WIN32 */
2125 if (function == NULL)
2127 buf[long_start + 1] = c;
2128 #ifdef WIN32
2129 // Restore the part of the long name that was damaged by
2130 // appending the '@nn'.
2131 memcpy ((buf + long_start + 1 + 1), long_nm_sv, sizeof (long_nm_sv));
2132 #endif /* WIN32 */
2133 function = _Jv_FindSymbolInExecutable (buf + 1);
2134 if (function == NULL)
2136 #ifdef WIN32
2137 strcat (buf, asz_buf);
2138 function = _Jv_FindSymbolInExecutable (buf);
2139 if (function == NULL)
2140 function = _Jv_FindSymbolInExecutable (buf + 1);
2142 if (function == NULL)
2143 #endif /* WIN32 */
2145 jstring str = JvNewStringUTF (name->data);
2146 throw new java::lang::UnsatisfiedLinkError (str);
2151 return function;
2154 #ifdef INTERPRETER
2156 // This function is the stub which is used to turn an ordinary (CNI)
2157 // method call into a JNI call.
2158 void
2159 _Jv_JNIMethod::call (ffi_cif *, void *ret, ffi_raw *args, void *__this)
2161 _Jv_JNIMethod* _this = (_Jv_JNIMethod *) __this;
2163 JNIEnv *env = _Jv_GetJNIEnvNewFrame (_this->defining_class);
2165 // FIXME: we should mark every reference parameter as a local. For
2166 // now we assume a conservative GC, and we assume that the
2167 // references are on the stack somewhere.
2169 // We cache the value that we find, of course, but if we don't find
2170 // a value we don't cache that fact -- we might subsequently load a
2171 // library which finds the function in question.
2173 // Synchronize on a convenient object to ensure sanity in case two
2174 // threads reach this point for the same function at the same
2175 // time.
2176 JvSynchronize sync (global_ref_table);
2177 if (_this->function == NULL)
2179 int args_size = sizeof (JNIEnv *) + _this->args_raw_size;
2181 if (_this->self->accflags & java::lang::reflect::Modifier::STATIC)
2182 args_size += sizeof (_this->defining_class);
2184 _this->function = _Jv_LookupJNIMethod (_this->defining_class,
2185 _this->self->name,
2186 _this->self->signature,
2187 args_size);
2191 JvAssert (_this->args_raw_size % sizeof (ffi_raw) == 0);
2192 ffi_raw real_args[2 + _this->args_raw_size / sizeof (ffi_raw)];
2193 int offset = 0;
2195 // First argument is always the environment pointer.
2196 real_args[offset++].ptr = env;
2198 // For a static method, we pass in the Class. For non-static
2199 // methods, the `this' argument is already handled.
2200 if ((_this->self->accflags & java::lang::reflect::Modifier::STATIC))
2201 real_args[offset++].ptr = _this->defining_class;
2203 // In libgcj, the callee synchronizes.
2204 jobject sync = NULL;
2205 if ((_this->self->accflags & java::lang::reflect::Modifier::SYNCHRONIZED))
2207 if ((_this->self->accflags & java::lang::reflect::Modifier::STATIC))
2208 sync = _this->defining_class;
2209 else
2210 sync = (jobject) args[0].ptr;
2211 _Jv_MonitorEnter (sync);
2214 // Copy over passed-in arguments.
2215 memcpy (&real_args[offset], args, _this->args_raw_size);
2217 // The actual call to the JNI function.
2218 ffi_raw_call (&_this->jni_cif, (void (*)()) _this->function,
2219 ret, real_args);
2221 if (sync != NULL)
2222 _Jv_MonitorExit (sync);
2224 _Jv_JNI_PopSystemFrame (env);
2227 #endif /* INTERPRETER */
2232 // Invocation API.
2235 // An internal helper function.
2236 static jint
2237 _Jv_JNI_AttachCurrentThread (JavaVM *, jstring name, void **penv,
2238 void *args, jboolean is_daemon)
2240 JavaVMAttachArgs *attach = reinterpret_cast<JavaVMAttachArgs *> (args);
2241 java::lang::ThreadGroup *group = NULL;
2243 if (attach)
2245 // FIXME: do we really want to support 1.1?
2246 if (attach->version != JNI_VERSION_1_4
2247 && attach->version != JNI_VERSION_1_2
2248 && attach->version != JNI_VERSION_1_1)
2249 return JNI_EVERSION;
2251 JvAssert (java::lang::ThreadGroup::class$.isInstance (attach->group));
2252 group = reinterpret_cast<java::lang::ThreadGroup *> (attach->group);
2255 // Attaching an already-attached thread is a no-op.
2256 if (_Jv_GetCurrentJNIEnv () != NULL)
2257 return 0;
2259 JNIEnv *env = (JNIEnv *) _Jv_MallocUnchecked (sizeof (JNIEnv));
2260 if (env == NULL)
2261 return JNI_ERR;
2262 env->p = &_Jv_JNIFunctions;
2263 env->ex = NULL;
2264 env->klass = NULL;
2265 env->locals
2266 = (_Jv_JNI_LocalFrame *) _Jv_MallocUnchecked (sizeof (_Jv_JNI_LocalFrame)
2267 + (FRAME_SIZE
2268 * sizeof (jobject)));
2269 if (env->locals == NULL)
2271 _Jv_Free (env);
2272 return JNI_ERR;
2275 env->locals->marker = MARK_SYSTEM;
2276 env->locals->size = FRAME_SIZE;
2277 env->locals->next = NULL;
2279 for (int i = 0; i < env->locals->size; ++i)
2280 env->locals->vec[i] = NULL;
2282 *penv = reinterpret_cast<void *> (env);
2284 // This thread might already be a Java thread -- this function might
2285 // have been called simply to set the new JNIEnv.
2286 if (_Jv_ThreadCurrent () == NULL)
2290 if (is_daemon)
2291 _Jv_AttachCurrentThreadAsDaemon (name, group);
2292 else
2293 _Jv_AttachCurrentThread (name, group);
2295 catch (jthrowable t)
2297 return JNI_ERR;
2300 _Jv_SetCurrentJNIEnv (env);
2302 return 0;
2305 // This is the one actually used by JNI.
2306 static jint
2307 (JNICALL _Jv_JNI_AttachCurrentThread) (JavaVM *vm, void **penv, void *args)
2309 return _Jv_JNI_AttachCurrentThread (vm, NULL, penv, args, false);
2312 static jint
2313 (JNICALL _Jv_JNI_AttachCurrentThreadAsDaemon) (JavaVM *vm, void **penv,
2314 void *args)
2316 return _Jv_JNI_AttachCurrentThread (vm, NULL, penv, args, true);
2319 static jint
2320 (JNICALL _Jv_JNI_DestroyJavaVM) (JavaVM *vm)
2322 JvAssert (the_vm && vm == the_vm);
2324 JNIEnv *env;
2325 if (_Jv_ThreadCurrent () != NULL)
2327 jstring main_name;
2328 // This sucks.
2331 main_name = JvNewStringLatin1 ("main");
2333 catch (jthrowable t)
2335 return JNI_ERR;
2338 jint r = _Jv_JNI_AttachCurrentThread (vm, main_name,
2339 reinterpret_cast<void **> (&env),
2340 NULL, false);
2341 if (r < 0)
2342 return r;
2344 else
2345 env = _Jv_GetCurrentJNIEnv ();
2347 _Jv_ThreadWait ();
2349 // Docs say that this always returns an error code.
2350 return JNI_ERR;
2353 jint
2354 (JNICALL _Jv_JNI_DetachCurrentThread) (JavaVM *)
2356 jint code = _Jv_DetachCurrentThread ();
2357 return code ? JNI_EDETACHED : 0;
2360 static jint
2361 (JNICALL _Jv_JNI_GetEnv) (JavaVM *, void **penv, jint version)
2363 if (_Jv_ThreadCurrent () == NULL)
2365 *penv = NULL;
2366 return JNI_EDETACHED;
2369 #ifdef ENABLE_JVMPI
2370 // Handle JVMPI requests.
2371 if (version == JVMPI_VERSION_1)
2373 *penv = (void *) &_Jv_JVMPI_Interface;
2374 return 0;
2376 #endif
2378 // FIXME: do we really want to support 1.1?
2379 if (version != JNI_VERSION_1_4 && version != JNI_VERSION_1_2
2380 && version != JNI_VERSION_1_1)
2382 *penv = NULL;
2383 return JNI_EVERSION;
2386 *penv = (void *) _Jv_GetCurrentJNIEnv ();
2387 return 0;
2390 JNIEXPORT jint JNICALL
2391 JNI_GetDefaultJavaVMInitArgs (void *args)
2393 jint version = * (jint *) args;
2394 // Here we only support 1.2 and 1.4.
2395 if (version != JNI_VERSION_1_2 && version != JNI_VERSION_1_4)
2396 return JNI_EVERSION;
2398 JavaVMInitArgs *ia = reinterpret_cast<JavaVMInitArgs *> (args);
2399 ia->version = JNI_VERSION_1_4;
2400 ia->nOptions = 0;
2401 ia->options = NULL;
2402 ia->ignoreUnrecognized = true;
2404 return 0;
2407 JNIEXPORT jint JNICALL
2408 JNI_CreateJavaVM (JavaVM **vm, void **penv, void *args)
2410 JvAssert (! the_vm);
2412 _Jv_CreateJavaVM (NULL);
2414 // FIXME: synchronize
2415 JavaVM *nvm = (JavaVM *) _Jv_MallocUnchecked (sizeof (JavaVM));
2416 if (nvm == NULL)
2417 return JNI_ERR;
2418 nvm->functions = &_Jv_JNI_InvokeFunctions;
2420 // Parse the arguments.
2421 if (args != NULL)
2423 jint version = * (jint *) args;
2424 // We only support 1.2 and 1.4.
2425 if (version != JNI_VERSION_1_2 && version != JNI_VERSION_1_4)
2426 return JNI_EVERSION;
2427 JavaVMInitArgs *ia = reinterpret_cast<JavaVMInitArgs *> (args);
2428 for (int i = 0; i < ia->nOptions; ++i)
2430 if (! strcmp (ia->options[i].optionString, "vfprintf")
2431 || ! strcmp (ia->options[i].optionString, "exit")
2432 || ! strcmp (ia->options[i].optionString, "abort"))
2434 // We are required to recognize these, but for now we
2435 // don't handle them in any way. FIXME.
2436 continue;
2438 else if (! strncmp (ia->options[i].optionString,
2439 "-verbose", sizeof ("-verbose") - 1))
2441 // We don't do anything with this option either. We
2442 // might want to make sure the argument is valid, but we
2443 // don't really care all that much for now.
2444 continue;
2446 else if (! strncmp (ia->options[i].optionString, "-D", 2))
2448 // FIXME.
2449 continue;
2451 else if (ia->ignoreUnrecognized)
2453 if (ia->options[i].optionString[0] == '_'
2454 || ! strncmp (ia->options[i].optionString, "-X", 2))
2455 continue;
2458 return JNI_ERR;
2462 jint r =_Jv_JNI_AttachCurrentThread (nvm, penv, NULL);
2463 if (r < 0)
2464 return r;
2466 the_vm = nvm;
2467 *vm = the_vm;
2469 return 0;
2472 JNIEXPORT jint JNICALL
2473 JNI_GetCreatedJavaVMs (JavaVM **vm_buffer, jsize buf_len, jsize *n_vms)
2475 if (buf_len <= 0)
2476 return JNI_ERR;
2478 // We only support a single VM.
2479 if (the_vm != NULL)
2481 vm_buffer[0] = the_vm;
2482 *n_vms = 1;
2484 else
2485 *n_vms = 0;
2486 return 0;
2489 JavaVM *
2490 _Jv_GetJavaVM ()
2492 // FIXME: synchronize
2493 if (! the_vm)
2495 JavaVM *nvm = (JavaVM *) _Jv_MallocUnchecked (sizeof (JavaVM));
2496 if (nvm != NULL)
2497 nvm->functions = &_Jv_JNI_InvokeFunctions;
2498 the_vm = nvm;
2501 // If this is a Java thread, we want to make sure it has an
2502 // associated JNIEnv.
2503 if (_Jv_ThreadCurrent () != NULL)
2505 void *ignore;
2506 _Jv_JNI_AttachCurrentThread (the_vm, &ignore, NULL);
2509 return the_vm;
2512 static jint
2513 (JNICALL _Jv_JNI_GetJavaVM) (JNIEnv *, JavaVM **vm)
2515 *vm = _Jv_GetJavaVM ();
2516 return *vm == NULL ? JNI_ERR : JNI_OK;
2521 #define RESERVED NULL
2523 struct JNINativeInterface _Jv_JNIFunctions =
2525 RESERVED,
2526 RESERVED,
2527 RESERVED,
2528 RESERVED,
2529 _Jv_JNI_GetVersion, // GetVersion
2530 _Jv_JNI_DefineClass, // DefineClass
2531 _Jv_JNI_FindClass, // FindClass
2532 _Jv_JNI_FromReflectedMethod, // FromReflectedMethod
2533 _Jv_JNI_FromReflectedField, // FromReflectedField
2534 _Jv_JNI_ToReflectedMethod, // ToReflectedMethod
2535 _Jv_JNI_GetSuperclass, // GetSuperclass
2536 _Jv_JNI_IsAssignableFrom, // IsAssignableFrom
2537 _Jv_JNI_ToReflectedField, // ToReflectedField
2538 _Jv_JNI_Throw, // Throw
2539 _Jv_JNI_ThrowNew, // ThrowNew
2540 _Jv_JNI_ExceptionOccurred, // ExceptionOccurred
2541 _Jv_JNI_ExceptionDescribe, // ExceptionDescribe
2542 _Jv_JNI_ExceptionClear, // ExceptionClear
2543 _Jv_JNI_FatalError, // FatalError
2545 _Jv_JNI_PushLocalFrame, // PushLocalFrame
2546 _Jv_JNI_PopLocalFrame, // PopLocalFrame
2547 _Jv_JNI_NewGlobalRef, // NewGlobalRef
2548 _Jv_JNI_DeleteGlobalRef, // DeleteGlobalRef
2549 _Jv_JNI_DeleteLocalRef, // DeleteLocalRef
2551 _Jv_JNI_IsSameObject, // IsSameObject
2553 _Jv_JNI_NewLocalRef, // NewLocalRef
2554 _Jv_JNI_EnsureLocalCapacity, // EnsureLocalCapacity
2556 _Jv_JNI_AllocObject, // AllocObject
2557 _Jv_JNI_NewObject, // NewObject
2558 _Jv_JNI_NewObjectV, // NewObjectV
2559 _Jv_JNI_NewObjectA, // NewObjectA
2560 _Jv_JNI_GetObjectClass, // GetObjectClass
2561 _Jv_JNI_IsInstanceOf, // IsInstanceOf
2562 _Jv_JNI_GetAnyMethodID<false>, // GetMethodID
2564 _Jv_JNI_CallMethod<jobject>, // CallObjectMethod
2565 _Jv_JNI_CallMethodV<jobject>, // CallObjectMethodV
2566 _Jv_JNI_CallMethodA<jobject>, // CallObjectMethodA
2567 _Jv_JNI_CallMethod<jboolean>, // CallBooleanMethod
2568 _Jv_JNI_CallMethodV<jboolean>, // CallBooleanMethodV
2569 _Jv_JNI_CallMethodA<jboolean>, // CallBooleanMethodA
2570 _Jv_JNI_CallMethod<jbyte>, // CallByteMethod
2571 _Jv_JNI_CallMethodV<jbyte>, // CallByteMethodV
2572 _Jv_JNI_CallMethodA<jbyte>, // CallByteMethodA
2573 _Jv_JNI_CallMethod<jchar>, // CallCharMethod
2574 _Jv_JNI_CallMethodV<jchar>, // CallCharMethodV
2575 _Jv_JNI_CallMethodA<jchar>, // CallCharMethodA
2576 _Jv_JNI_CallMethod<jshort>, // CallShortMethod
2577 _Jv_JNI_CallMethodV<jshort>, // CallShortMethodV
2578 _Jv_JNI_CallMethodA<jshort>, // CallShortMethodA
2579 _Jv_JNI_CallMethod<jint>, // CallIntMethod
2580 _Jv_JNI_CallMethodV<jint>, // CallIntMethodV
2581 _Jv_JNI_CallMethodA<jint>, // CallIntMethodA
2582 _Jv_JNI_CallMethod<jlong>, // CallLongMethod
2583 _Jv_JNI_CallMethodV<jlong>, // CallLongMethodV
2584 _Jv_JNI_CallMethodA<jlong>, // CallLongMethodA
2585 _Jv_JNI_CallMethod<jfloat>, // CallFloatMethod
2586 _Jv_JNI_CallMethodV<jfloat>, // CallFloatMethodV
2587 _Jv_JNI_CallMethodA<jfloat>, // CallFloatMethodA
2588 _Jv_JNI_CallMethod<jdouble>, // CallDoubleMethod
2589 _Jv_JNI_CallMethodV<jdouble>, // CallDoubleMethodV
2590 _Jv_JNI_CallMethodA<jdouble>, // CallDoubleMethodA
2591 _Jv_JNI_CallVoidMethod, // CallVoidMethod
2592 _Jv_JNI_CallVoidMethodV, // CallVoidMethodV
2593 _Jv_JNI_CallVoidMethodA, // CallVoidMethodA
2595 // Nonvirtual method invocation functions follow.
2596 _Jv_JNI_CallAnyMethod<jobject, nonvirtual>, // CallNonvirtualObjectMethod
2597 _Jv_JNI_CallAnyMethodV<jobject, nonvirtual>, // CallNonvirtualObjectMethodV
2598 _Jv_JNI_CallAnyMethodA<jobject, nonvirtual>, // CallNonvirtualObjectMethodA
2599 _Jv_JNI_CallAnyMethod<jboolean, nonvirtual>, // CallNonvirtualBooleanMethod
2600 _Jv_JNI_CallAnyMethodV<jboolean, nonvirtual>, // CallNonvirtualBooleanMethodV
2601 _Jv_JNI_CallAnyMethodA<jboolean, nonvirtual>, // CallNonvirtualBooleanMethodA
2602 _Jv_JNI_CallAnyMethod<jbyte, nonvirtual>, // CallNonvirtualByteMethod
2603 _Jv_JNI_CallAnyMethodV<jbyte, nonvirtual>, // CallNonvirtualByteMethodV
2604 _Jv_JNI_CallAnyMethodA<jbyte, nonvirtual>, // CallNonvirtualByteMethodA
2605 _Jv_JNI_CallAnyMethod<jchar, nonvirtual>, // CallNonvirtualCharMethod
2606 _Jv_JNI_CallAnyMethodV<jchar, nonvirtual>, // CallNonvirtualCharMethodV
2607 _Jv_JNI_CallAnyMethodA<jchar, nonvirtual>, // CallNonvirtualCharMethodA
2608 _Jv_JNI_CallAnyMethod<jshort, nonvirtual>, // CallNonvirtualShortMethod
2609 _Jv_JNI_CallAnyMethodV<jshort, nonvirtual>, // CallNonvirtualShortMethodV
2610 _Jv_JNI_CallAnyMethodA<jshort, nonvirtual>, // CallNonvirtualShortMethodA
2611 _Jv_JNI_CallAnyMethod<jint, nonvirtual>, // CallNonvirtualIntMethod
2612 _Jv_JNI_CallAnyMethodV<jint, nonvirtual>, // CallNonvirtualIntMethodV
2613 _Jv_JNI_CallAnyMethodA<jint, nonvirtual>, // CallNonvirtualIntMethodA
2614 _Jv_JNI_CallAnyMethod<jlong, nonvirtual>, // CallNonvirtualLongMethod
2615 _Jv_JNI_CallAnyMethodV<jlong, nonvirtual>, // CallNonvirtualLongMethodV
2616 _Jv_JNI_CallAnyMethodA<jlong, nonvirtual>, // CallNonvirtualLongMethodA
2617 _Jv_JNI_CallAnyMethod<jfloat, nonvirtual>, // CallNonvirtualFloatMethod
2618 _Jv_JNI_CallAnyMethodV<jfloat, nonvirtual>, // CallNonvirtualFloatMethodV
2619 _Jv_JNI_CallAnyMethodA<jfloat, nonvirtual>, // CallNonvirtualFloatMethodA
2620 _Jv_JNI_CallAnyMethod<jdouble, nonvirtual>, // CallNonvirtualDoubleMethod
2621 _Jv_JNI_CallAnyMethodV<jdouble, nonvirtual>, // CallNonvirtualDoubleMethodV
2622 _Jv_JNI_CallAnyMethodA<jdouble, nonvirtual>, // CallNonvirtualDoubleMethodA
2623 _Jv_JNI_CallAnyVoidMethod<nonvirtual>, // CallNonvirtualVoidMethod
2624 _Jv_JNI_CallAnyVoidMethodV<nonvirtual>, // CallNonvirtualVoidMethodV
2625 _Jv_JNI_CallAnyVoidMethodA<nonvirtual>, // CallNonvirtualVoidMethodA
2627 _Jv_JNI_GetAnyFieldID<false>, // GetFieldID
2628 _Jv_JNI_GetField<jobject>, // GetObjectField
2629 _Jv_JNI_GetField<jboolean>, // GetBooleanField
2630 _Jv_JNI_GetField<jbyte>, // GetByteField
2631 _Jv_JNI_GetField<jchar>, // GetCharField
2632 _Jv_JNI_GetField<jshort>, // GetShortField
2633 _Jv_JNI_GetField<jint>, // GetIntField
2634 _Jv_JNI_GetField<jlong>, // GetLongField
2635 _Jv_JNI_GetField<jfloat>, // GetFloatField
2636 _Jv_JNI_GetField<jdouble>, // GetDoubleField
2637 _Jv_JNI_SetField, // SetObjectField
2638 _Jv_JNI_SetField, // SetBooleanField
2639 _Jv_JNI_SetField, // SetByteField
2640 _Jv_JNI_SetField, // SetCharField
2641 _Jv_JNI_SetField, // SetShortField
2642 _Jv_JNI_SetField, // SetIntField
2643 _Jv_JNI_SetField, // SetLongField
2644 _Jv_JNI_SetField, // SetFloatField
2645 _Jv_JNI_SetField, // SetDoubleField
2646 _Jv_JNI_GetAnyMethodID<true>, // GetStaticMethodID
2648 _Jv_JNI_CallStaticMethod<jobject>, // CallStaticObjectMethod
2649 _Jv_JNI_CallStaticMethodV<jobject>, // CallStaticObjectMethodV
2650 _Jv_JNI_CallStaticMethodA<jobject>, // CallStaticObjectMethodA
2651 _Jv_JNI_CallStaticMethod<jboolean>, // CallStaticBooleanMethod
2652 _Jv_JNI_CallStaticMethodV<jboolean>, // CallStaticBooleanMethodV
2653 _Jv_JNI_CallStaticMethodA<jboolean>, // CallStaticBooleanMethodA
2654 _Jv_JNI_CallStaticMethod<jbyte>, // CallStaticByteMethod
2655 _Jv_JNI_CallStaticMethodV<jbyte>, // CallStaticByteMethodV
2656 _Jv_JNI_CallStaticMethodA<jbyte>, // CallStaticByteMethodA
2657 _Jv_JNI_CallStaticMethod<jchar>, // CallStaticCharMethod
2658 _Jv_JNI_CallStaticMethodV<jchar>, // CallStaticCharMethodV
2659 _Jv_JNI_CallStaticMethodA<jchar>, // CallStaticCharMethodA
2660 _Jv_JNI_CallStaticMethod<jshort>, // CallStaticShortMethod
2661 _Jv_JNI_CallStaticMethodV<jshort>, // CallStaticShortMethodV
2662 _Jv_JNI_CallStaticMethodA<jshort>, // CallStaticShortMethodA
2663 _Jv_JNI_CallStaticMethod<jint>, // CallStaticIntMethod
2664 _Jv_JNI_CallStaticMethodV<jint>, // CallStaticIntMethodV
2665 _Jv_JNI_CallStaticMethodA<jint>, // CallStaticIntMethodA
2666 _Jv_JNI_CallStaticMethod<jlong>, // CallStaticLongMethod
2667 _Jv_JNI_CallStaticMethodV<jlong>, // CallStaticLongMethodV
2668 _Jv_JNI_CallStaticMethodA<jlong>, // CallStaticLongMethodA
2669 _Jv_JNI_CallStaticMethod<jfloat>, // CallStaticFloatMethod
2670 _Jv_JNI_CallStaticMethodV<jfloat>, // CallStaticFloatMethodV
2671 _Jv_JNI_CallStaticMethodA<jfloat>, // CallStaticFloatMethodA
2672 _Jv_JNI_CallStaticMethod<jdouble>, // CallStaticDoubleMethod
2673 _Jv_JNI_CallStaticMethodV<jdouble>, // CallStaticDoubleMethodV
2674 _Jv_JNI_CallStaticMethodA<jdouble>, // CallStaticDoubleMethodA
2675 _Jv_JNI_CallStaticVoidMethod, // CallStaticVoidMethod
2676 _Jv_JNI_CallStaticVoidMethodV, // CallStaticVoidMethodV
2677 _Jv_JNI_CallStaticVoidMethodA, // CallStaticVoidMethodA
2679 _Jv_JNI_GetAnyFieldID<true>, // GetStaticFieldID
2680 _Jv_JNI_GetStaticField<jobject>, // GetStaticObjectField
2681 _Jv_JNI_GetStaticField<jboolean>, // GetStaticBooleanField
2682 _Jv_JNI_GetStaticField<jbyte>, // GetStaticByteField
2683 _Jv_JNI_GetStaticField<jchar>, // GetStaticCharField
2684 _Jv_JNI_GetStaticField<jshort>, // GetStaticShortField
2685 _Jv_JNI_GetStaticField<jint>, // GetStaticIntField
2686 _Jv_JNI_GetStaticField<jlong>, // GetStaticLongField
2687 _Jv_JNI_GetStaticField<jfloat>, // GetStaticFloatField
2688 _Jv_JNI_GetStaticField<jdouble>, // GetStaticDoubleField
2689 _Jv_JNI_SetStaticField, // SetStaticObjectField
2690 _Jv_JNI_SetStaticField, // SetStaticBooleanField
2691 _Jv_JNI_SetStaticField, // SetStaticByteField
2692 _Jv_JNI_SetStaticField, // SetStaticCharField
2693 _Jv_JNI_SetStaticField, // SetStaticShortField
2694 _Jv_JNI_SetStaticField, // SetStaticIntField
2695 _Jv_JNI_SetStaticField, // SetStaticLongField
2696 _Jv_JNI_SetStaticField, // SetStaticFloatField
2697 _Jv_JNI_SetStaticField, // SetStaticDoubleField
2698 _Jv_JNI_NewString, // NewString
2699 _Jv_JNI_GetStringLength, // GetStringLength
2700 _Jv_JNI_GetStringChars, // GetStringChars
2701 _Jv_JNI_ReleaseStringChars, // ReleaseStringChars
2702 _Jv_JNI_NewStringUTF, // NewStringUTF
2703 _Jv_JNI_GetStringUTFLength, // GetStringUTFLength
2704 _Jv_JNI_GetStringUTFChars, // GetStringUTFChars
2705 _Jv_JNI_ReleaseStringUTFChars, // ReleaseStringUTFChars
2706 _Jv_JNI_GetArrayLength, // GetArrayLength
2707 _Jv_JNI_NewObjectArray, // NewObjectArray
2708 _Jv_JNI_GetObjectArrayElement, // GetObjectArrayElement
2709 _Jv_JNI_SetObjectArrayElement, // SetObjectArrayElement
2710 _Jv_JNI_NewPrimitiveArray<jboolean, JvPrimClass (boolean)>,
2711 // NewBooleanArray
2712 _Jv_JNI_NewPrimitiveArray<jbyte, JvPrimClass (byte)>, // NewByteArray
2713 _Jv_JNI_NewPrimitiveArray<jchar, JvPrimClass (char)>, // NewCharArray
2714 _Jv_JNI_NewPrimitiveArray<jshort, JvPrimClass (short)>, // NewShortArray
2715 _Jv_JNI_NewPrimitiveArray<jint, JvPrimClass (int)>, // NewIntArray
2716 _Jv_JNI_NewPrimitiveArray<jlong, JvPrimClass (long)>, // NewLongArray
2717 _Jv_JNI_NewPrimitiveArray<jfloat, JvPrimClass (float)>, // NewFloatArray
2718 _Jv_JNI_NewPrimitiveArray<jdouble, JvPrimClass (double)>, // NewDoubleArray
2719 _Jv_JNI_GetPrimitiveArrayElements<jboolean, JvPrimClass (boolean)>,
2720 // GetBooleanArrayElements
2721 _Jv_JNI_GetPrimitiveArrayElements<jbyte, JvPrimClass (byte)>,
2722 // GetByteArrayElements
2723 _Jv_JNI_GetPrimitiveArrayElements<jchar, JvPrimClass (char)>,
2724 // GetCharArrayElements
2725 _Jv_JNI_GetPrimitiveArrayElements<jshort, JvPrimClass (short)>,
2726 // GetShortArrayElements
2727 _Jv_JNI_GetPrimitiveArrayElements<jint, JvPrimClass (int)>,
2728 // GetIntArrayElements
2729 _Jv_JNI_GetPrimitiveArrayElements<jlong, JvPrimClass (long)>,
2730 // GetLongArrayElements
2731 _Jv_JNI_GetPrimitiveArrayElements<jfloat, JvPrimClass (float)>,
2732 // GetFloatArrayElements
2733 _Jv_JNI_GetPrimitiveArrayElements<jdouble, JvPrimClass (double)>,
2734 // GetDoubleArrayElements
2735 _Jv_JNI_ReleasePrimitiveArrayElements<jboolean, JvPrimClass (boolean)>,
2736 // ReleaseBooleanArrayElements
2737 _Jv_JNI_ReleasePrimitiveArrayElements<jbyte, JvPrimClass (byte)>,
2738 // ReleaseByteArrayElements
2739 _Jv_JNI_ReleasePrimitiveArrayElements<jchar, JvPrimClass (char)>,
2740 // ReleaseCharArrayElements
2741 _Jv_JNI_ReleasePrimitiveArrayElements<jshort, JvPrimClass (short)>,
2742 // ReleaseShortArrayElements
2743 _Jv_JNI_ReleasePrimitiveArrayElements<jint, JvPrimClass (int)>,
2744 // ReleaseIntArrayElements
2745 _Jv_JNI_ReleasePrimitiveArrayElements<jlong, JvPrimClass (long)>,
2746 // ReleaseLongArrayElements
2747 _Jv_JNI_ReleasePrimitiveArrayElements<jfloat, JvPrimClass (float)>,
2748 // ReleaseFloatArrayElements
2749 _Jv_JNI_ReleasePrimitiveArrayElements<jdouble, JvPrimClass (double)>,
2750 // ReleaseDoubleArrayElements
2751 _Jv_JNI_GetPrimitiveArrayRegion<jboolean, JvPrimClass (boolean)>,
2752 // GetBooleanArrayRegion
2753 _Jv_JNI_GetPrimitiveArrayRegion<jbyte, JvPrimClass (byte)>,
2754 // GetByteArrayRegion
2755 _Jv_JNI_GetPrimitiveArrayRegion<jchar, JvPrimClass (char)>,
2756 // GetCharArrayRegion
2757 _Jv_JNI_GetPrimitiveArrayRegion<jshort, JvPrimClass (short)>,
2758 // GetShortArrayRegion
2759 _Jv_JNI_GetPrimitiveArrayRegion<jint, JvPrimClass (int)>,
2760 // GetIntArrayRegion
2761 _Jv_JNI_GetPrimitiveArrayRegion<jlong, JvPrimClass (long)>,
2762 // GetLongArrayRegion
2763 _Jv_JNI_GetPrimitiveArrayRegion<jfloat, JvPrimClass (float)>,
2764 // GetFloatArrayRegion
2765 _Jv_JNI_GetPrimitiveArrayRegion<jdouble, JvPrimClass (double)>,
2766 // GetDoubleArrayRegion
2767 _Jv_JNI_SetPrimitiveArrayRegion<jboolean, JvPrimClass (boolean)>,
2768 // SetBooleanArrayRegion
2769 _Jv_JNI_SetPrimitiveArrayRegion<jbyte, JvPrimClass (byte)>,
2770 // SetByteArrayRegion
2771 _Jv_JNI_SetPrimitiveArrayRegion<jchar, JvPrimClass (char)>,
2772 // SetCharArrayRegion
2773 _Jv_JNI_SetPrimitiveArrayRegion<jshort, JvPrimClass (short)>,
2774 // SetShortArrayRegion
2775 _Jv_JNI_SetPrimitiveArrayRegion<jint, JvPrimClass (int)>,
2776 // SetIntArrayRegion
2777 _Jv_JNI_SetPrimitiveArrayRegion<jlong, JvPrimClass (long)>,
2778 // SetLongArrayRegion
2779 _Jv_JNI_SetPrimitiveArrayRegion<jfloat, JvPrimClass (float)>,
2780 // SetFloatArrayRegion
2781 _Jv_JNI_SetPrimitiveArrayRegion<jdouble, JvPrimClass (double)>,
2782 // SetDoubleArrayRegion
2783 _Jv_JNI_RegisterNatives, // RegisterNatives
2784 _Jv_JNI_UnregisterNatives, // UnregisterNatives
2785 _Jv_JNI_MonitorEnter, // MonitorEnter
2786 _Jv_JNI_MonitorExit, // MonitorExit
2787 _Jv_JNI_GetJavaVM, // GetJavaVM
2789 _Jv_JNI_GetStringRegion, // GetStringRegion
2790 _Jv_JNI_GetStringUTFRegion, // GetStringUTFRegion
2791 _Jv_JNI_GetPrimitiveArrayCritical, // GetPrimitiveArrayCritical
2792 _Jv_JNI_ReleasePrimitiveArrayCritical, // ReleasePrimitiveArrayCritical
2793 _Jv_JNI_GetStringCritical, // GetStringCritical
2794 _Jv_JNI_ReleaseStringCritical, // ReleaseStringCritical
2796 _Jv_JNI_NewWeakGlobalRef, // NewWeakGlobalRef
2797 _Jv_JNI_DeleteWeakGlobalRef, // DeleteWeakGlobalRef
2799 _Jv_JNI_ExceptionCheck, // ExceptionCheck
2801 _Jv_JNI_NewDirectByteBuffer, // NewDirectByteBuffer
2802 _Jv_JNI_GetDirectBufferAddress, // GetDirectBufferAddress
2803 _Jv_JNI_GetDirectBufferCapacity // GetDirectBufferCapacity
2806 struct JNIInvokeInterface _Jv_JNI_InvokeFunctions =
2808 RESERVED,
2809 RESERVED,
2810 RESERVED,
2812 _Jv_JNI_DestroyJavaVM,
2813 _Jv_JNI_AttachCurrentThread,
2814 _Jv_JNI_DetachCurrentThread,
2815 _Jv_JNI_GetEnv,
2816 _Jv_JNI_AttachCurrentThreadAsDaemon