PR preprocessor/15167
[official-gcc.git] / libjava / jni.cc
blob6138334ebaffce829ed884d9cdda77c06b93d349
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] = &java::lang::String::class$;
568 Constructor *cons = clazz->getConstructor (argtypes);
570 jobjectArray values = JvNewObjectArray (1, &java::lang::String::class$,
571 NULL);
572 jobject *velts = elements (values);
573 velts[0] = JvNewStringUTF (message);
575 jobject obj = cons->newInstance (values);
577 env->ex = reinterpret_cast<jthrowable> (obj);
579 catch (jthrowable t)
581 env->ex = t;
582 r = JNI_ERR;
585 return r;
588 static jthrowable JNICALL
589 _Jv_JNI_ExceptionOccurred (JNIEnv *env)
591 return (jthrowable) wrap_value (env, env->ex);
594 static void JNICALL
595 _Jv_JNI_ExceptionDescribe (JNIEnv *env)
597 if (env->ex != NULL)
598 env->ex->printStackTrace();
601 static void JNICALL
602 _Jv_JNI_ExceptionClear (JNIEnv *env)
604 env->ex = NULL;
607 static jboolean JNICALL
608 _Jv_JNI_ExceptionCheck (JNIEnv *env)
610 return env->ex != NULL;
613 static void JNICALL
614 _Jv_JNI_FatalError (JNIEnv *, const char *message)
616 JvFail (message);
621 static jboolean JNICALL
622 _Jv_JNI_IsSameObject (JNIEnv *, jobject obj1, jobject obj2)
624 return unwrap (obj1) == unwrap (obj2);
627 static jobject JNICALL
628 _Jv_JNI_AllocObject (JNIEnv *env, jclass clazz)
630 jobject obj = NULL;
631 using namespace java::lang::reflect;
635 clazz = unwrap (clazz);
636 JvAssert (clazz && ! clazz->isArray ());
637 if (clazz->isInterface() || Modifier::isAbstract(clazz->getModifiers()))
638 env->ex = new java::lang::InstantiationException ();
639 else
640 obj = _Jv_AllocObject (clazz);
642 catch (jthrowable t)
644 env->ex = t;
647 return wrap_value (env, obj);
650 static jclass JNICALL
651 _Jv_JNI_GetObjectClass (JNIEnv *env, jobject obj)
653 obj = unwrap (obj);
654 JvAssert (obj);
655 return (jclass) wrap_value (env, obj->getClass());
658 static jboolean JNICALL
659 _Jv_JNI_IsInstanceOf (JNIEnv *, jobject obj, jclass clazz)
661 return unwrap (clazz)->isInstance(unwrap (obj));
667 // This section concerns method invocation.
670 template<jboolean is_static>
671 static jmethodID JNICALL
672 _Jv_JNI_GetAnyMethodID (JNIEnv *env, jclass clazz,
673 const char *name, const char *sig)
677 clazz = unwrap (clazz);
678 _Jv_InitClass (clazz);
680 _Jv_Utf8Const *name_u = _Jv_makeUtf8Const ((char *) name, -1);
682 // FIXME: assume that SIG isn't too long.
683 int len = strlen (sig);
684 char s[len + 1];
685 for (int i = 0; i <= len; ++i)
686 s[i] = (sig[i] == '/') ? '.' : sig[i];
687 _Jv_Utf8Const *sig_u = _Jv_makeUtf8Const ((char *) s, -1);
689 JvAssert (! clazz->isPrimitive());
691 using namespace java::lang::reflect;
693 while (clazz != NULL)
695 jint count = JvNumMethods (clazz);
696 jmethodID meth = JvGetFirstMethod (clazz);
698 for (jint i = 0; i < count; ++i)
700 if (((is_static && Modifier::isStatic (meth->accflags))
701 || (! is_static && ! Modifier::isStatic (meth->accflags)))
702 && _Jv_equalUtf8Consts (meth->name, name_u)
703 && _Jv_equalUtf8Consts (meth->signature, sig_u))
704 return meth;
706 meth = meth->getNextMethod();
709 clazz = clazz->getSuperclass ();
712 java::lang::StringBuffer *name_sig =
713 new java::lang::StringBuffer (JvNewStringUTF (name));
714 name_sig->append ((jchar) ' ')->append (JvNewStringUTF (s));
715 env->ex = new java::lang::NoSuchMethodError (name_sig->toString ());
717 catch (jthrowable t)
719 env->ex = t;
722 return NULL;
725 // This is a helper function which turns a va_list into an array of
726 // `jvalue's. It needs signature information in order to do its work.
727 // The array of values must already be allocated.
728 static void
729 array_from_valist (jvalue *values, JArray<jclass> *arg_types, va_list vargs)
731 jclass *arg_elts = elements (arg_types);
732 for (int i = 0; i < arg_types->length; ++i)
734 // Here we assume that sizeof(int) >= sizeof(jint), because we
735 // use `int' when decoding the varargs. Likewise for
736 // float, and double. Also we assume that sizeof(jlong) >=
737 // sizeof(int), i.e. that jlong values are not further
738 // promoted.
739 JvAssert (sizeof (int) >= sizeof (jint));
740 JvAssert (sizeof (jlong) >= sizeof (int));
741 JvAssert (sizeof (double) >= sizeof (jfloat));
742 JvAssert (sizeof (double) >= sizeof (jdouble));
743 if (arg_elts[i] == JvPrimClass (byte))
744 values[i].b = (jbyte) va_arg (vargs, int);
745 else if (arg_elts[i] == JvPrimClass (short))
746 values[i].s = (jshort) va_arg (vargs, int);
747 else if (arg_elts[i] == JvPrimClass (int))
748 values[i].i = (jint) va_arg (vargs, int);
749 else if (arg_elts[i] == JvPrimClass (long))
750 values[i].j = (jlong) va_arg (vargs, jlong);
751 else if (arg_elts[i] == JvPrimClass (float))
752 values[i].f = (jfloat) va_arg (vargs, double);
753 else if (arg_elts[i] == JvPrimClass (double))
754 values[i].d = (jdouble) va_arg (vargs, double);
755 else if (arg_elts[i] == JvPrimClass (boolean))
756 values[i].z = (jboolean) va_arg (vargs, int);
757 else if (arg_elts[i] == JvPrimClass (char))
758 values[i].c = (jchar) va_arg (vargs, int);
759 else
761 // An object.
762 values[i].l = unwrap (va_arg (vargs, jobject));
767 // This can call any sort of method: virtual, "nonvirtual", static, or
768 // constructor.
769 template<typename T, invocation_type style>
770 static T JNICALL
771 _Jv_JNI_CallAnyMethodV (JNIEnv *env, jobject obj, jclass klass,
772 jmethodID id, va_list vargs)
774 obj = unwrap (obj);
775 klass = unwrap (klass);
777 jclass decl_class = klass ? klass : obj->getClass ();
778 JvAssert (decl_class != NULL);
780 jclass return_type;
781 JArray<jclass> *arg_types;
785 _Jv_GetTypesFromSignature (id, decl_class,
786 &arg_types, &return_type);
788 jvalue args[arg_types->length];
789 array_from_valist (args, arg_types, vargs);
791 // For constructors we need to pass the Class we are instantiating.
792 if (style == constructor)
793 return_type = klass;
795 jvalue result;
796 _Jv_CallAnyMethodA (obj, return_type, id,
797 style == constructor,
798 style == normal,
799 arg_types, args, &result);
801 return wrap_value (env, extract_from_jvalue<T>(result));
803 catch (jthrowable t)
805 env->ex = t;
808 return wrap_value (env, (T) 0);
811 template<typename T, invocation_type style>
812 static T JNICALL
813 _Jv_JNI_CallAnyMethod (JNIEnv *env, jobject obj, jclass klass,
814 jmethodID method, ...)
816 va_list args;
817 T result;
819 va_start (args, method);
820 result = _Jv_JNI_CallAnyMethodV<T, style> (env, obj, klass, method, args);
821 va_end (args);
823 return result;
826 template<typename T, invocation_type style>
827 static T JNICALL
828 _Jv_JNI_CallAnyMethodA (JNIEnv *env, jobject obj, jclass klass,
829 jmethodID id, jvalue *args)
831 obj = unwrap (obj);
832 klass = unwrap (klass);
834 jclass decl_class = klass ? klass : obj->getClass ();
835 JvAssert (decl_class != NULL);
837 jclass return_type;
838 JArray<jclass> *arg_types;
841 _Jv_GetTypesFromSignature (id, decl_class,
842 &arg_types, &return_type);
844 // For constructors we need to pass the Class we are instantiating.
845 if (style == constructor)
846 return_type = klass;
848 // Unwrap arguments as required. Eww.
849 jclass *type_elts = elements (arg_types);
850 jvalue arg_copy[arg_types->length];
851 for (int i = 0; i < arg_types->length; ++i)
853 if (type_elts[i]->isPrimitive ())
854 arg_copy[i] = args[i];
855 else
856 arg_copy[i].l = unwrap (args[i].l);
859 jvalue result;
860 _Jv_CallAnyMethodA (obj, return_type, id,
861 style == constructor,
862 style == normal,
863 arg_types, arg_copy, &result);
865 return wrap_value (env, extract_from_jvalue<T>(result));
867 catch (jthrowable t)
869 env->ex = t;
872 return wrap_value (env, (T) 0);
875 template<invocation_type style>
876 static void JNICALL
877 _Jv_JNI_CallAnyVoidMethodV (JNIEnv *env, jobject obj, jclass klass,
878 jmethodID id, va_list vargs)
880 obj = unwrap (obj);
881 klass = unwrap (klass);
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 style == normal,
903 arg_types, args, NULL);
905 catch (jthrowable t)
907 env->ex = t;
911 template<invocation_type style>
912 static void JNICALL
913 _Jv_JNI_CallAnyVoidMethod (JNIEnv *env, jobject obj, jclass klass,
914 jmethodID method, ...)
916 va_list args;
918 va_start (args, method);
919 _Jv_JNI_CallAnyVoidMethodV<style> (env, obj, klass, method, args);
920 va_end (args);
923 template<invocation_type style>
924 static void JNICALL
925 _Jv_JNI_CallAnyVoidMethodA (JNIEnv *env, jobject obj, jclass klass,
926 jmethodID id, jvalue *args)
928 jclass decl_class = klass ? klass : obj->getClass ();
929 JvAssert (decl_class != NULL);
931 jclass return_type;
932 JArray<jclass> *arg_types;
935 _Jv_GetTypesFromSignature (id, decl_class,
936 &arg_types, &return_type);
938 // Unwrap arguments as required. Eww.
939 jclass *type_elts = elements (arg_types);
940 jvalue arg_copy[arg_types->length];
941 for (int i = 0; i < arg_types->length; ++i)
943 if (type_elts[i]->isPrimitive ())
944 arg_copy[i] = args[i];
945 else
946 arg_copy[i].l = unwrap (args[i].l);
949 _Jv_CallAnyMethodA (obj, return_type, id,
950 style == constructor,
951 style == normal,
952 arg_types, args, NULL);
954 catch (jthrowable t)
956 env->ex = t;
960 // Functions with this signature are used to implement functions in
961 // the CallMethod family.
962 template<typename T>
963 static T JNICALL
964 _Jv_JNI_CallMethodV (JNIEnv *env, jobject obj,
965 jmethodID id, va_list args)
967 return _Jv_JNI_CallAnyMethodV<T, normal> (env, obj, NULL, id, args);
970 // Functions with this signature are used to implement functions in
971 // the CallMethod family.
972 template<typename T>
973 static T JNICALL
974 _Jv_JNI_CallMethod (JNIEnv *env, jobject obj, jmethodID id, ...)
976 va_list args;
977 T result;
979 va_start (args, id);
980 result = _Jv_JNI_CallAnyMethodV<T, normal> (env, obj, NULL, id, args);
981 va_end (args);
983 return result;
986 // Functions with this signature are used to implement functions in
987 // the CallMethod family.
988 template<typename T>
989 static T JNICALL
990 _Jv_JNI_CallMethodA (JNIEnv *env, jobject obj,
991 jmethodID id, jvalue *args)
993 return _Jv_JNI_CallAnyMethodA<T, normal> (env, obj, NULL, id, args);
996 static void JNICALL
997 _Jv_JNI_CallVoidMethodV (JNIEnv *env, jobject obj,
998 jmethodID id, va_list args)
1000 _Jv_JNI_CallAnyVoidMethodV<normal> (env, obj, NULL, id, args);
1003 static void JNICALL
1004 _Jv_JNI_CallVoidMethod (JNIEnv *env, jobject obj, jmethodID id, ...)
1006 va_list args;
1008 va_start (args, id);
1009 _Jv_JNI_CallAnyVoidMethodV<normal> (env, obj, NULL, id, args);
1010 va_end (args);
1013 static void JNICALL
1014 _Jv_JNI_CallVoidMethodA (JNIEnv *env, jobject obj,
1015 jmethodID id, jvalue *args)
1017 _Jv_JNI_CallAnyVoidMethodA<normal> (env, obj, NULL, id, args);
1020 // Functions with this signature are used to implement functions in
1021 // the CallStaticMethod family.
1022 template<typename T>
1023 static T JNICALL
1024 _Jv_JNI_CallStaticMethodV (JNIEnv *env, jclass klass,
1025 jmethodID id, va_list args)
1027 JvAssert (((id->accflags) & java::lang::reflect::Modifier::STATIC));
1028 JvAssert (java::lang::Class::class$.isInstance (unwrap (klass)));
1030 return _Jv_JNI_CallAnyMethodV<T, static_type> (env, NULL, klass, id, args);
1033 // Functions with this signature are used to implement functions in
1034 // the CallStaticMethod family.
1035 template<typename T>
1036 static T JNICALL
1037 _Jv_JNI_CallStaticMethod (JNIEnv *env, jclass klass,
1038 jmethodID id, ...)
1040 va_list args;
1041 T result;
1043 JvAssert (((id->accflags) & java::lang::reflect::Modifier::STATIC));
1044 JvAssert (java::lang::Class::class$.isInstance (unwrap (klass)));
1046 va_start (args, id);
1047 result = _Jv_JNI_CallAnyMethodV<T, static_type> (env, NULL, klass,
1048 id, args);
1049 va_end (args);
1051 return result;
1054 // Functions with this signature are used to implement functions in
1055 // the CallStaticMethod family.
1056 template<typename T>
1057 static T JNICALL
1058 _Jv_JNI_CallStaticMethodA (JNIEnv *env, jclass klass, jmethodID id,
1059 jvalue *args)
1061 JvAssert (((id->accflags) & java::lang::reflect::Modifier::STATIC));
1062 JvAssert (java::lang::Class::class$.isInstance (unwrap (klass)));
1064 return _Jv_JNI_CallAnyMethodA<T, static_type> (env, NULL, klass, id, args);
1067 static void JNICALL
1068 _Jv_JNI_CallStaticVoidMethodV (JNIEnv *env, jclass klass,
1069 jmethodID id, va_list args)
1071 _Jv_JNI_CallAnyVoidMethodV<static_type> (env, NULL, klass, id, args);
1074 static void JNICALL
1075 _Jv_JNI_CallStaticVoidMethod (JNIEnv *env, jclass klass,
1076 jmethodID id, ...)
1078 va_list args;
1080 va_start (args, id);
1081 _Jv_JNI_CallAnyVoidMethodV<static_type> (env, NULL, klass, id, args);
1082 va_end (args);
1085 static void JNICALL
1086 _Jv_JNI_CallStaticVoidMethodA (JNIEnv *env, jclass klass,
1087 jmethodID id, jvalue *args)
1089 _Jv_JNI_CallAnyVoidMethodA<static_type> (env, NULL, klass, id, args);
1092 static jobject JNICALL
1093 _Jv_JNI_NewObjectV (JNIEnv *env, jclass klass,
1094 jmethodID id, va_list args)
1096 JvAssert (klass && ! klass->isArray ());
1097 JvAssert (! strcmp (id->name->data, "<init>")
1098 && id->signature->length > 2
1099 && id->signature->data[0] == '('
1100 && ! strcmp (&id->signature->data[id->signature->length - 2],
1101 ")V"));
1103 return _Jv_JNI_CallAnyMethodV<jobject, constructor> (env, NULL, klass,
1104 id, args);
1107 static jobject JNICALL
1108 _Jv_JNI_NewObject (JNIEnv *env, jclass klass, jmethodID id, ...)
1110 JvAssert (klass && ! klass->isArray ());
1111 JvAssert (! strcmp (id->name->data, "<init>")
1112 && id->signature->length > 2
1113 && id->signature->data[0] == '('
1114 && ! strcmp (&id->signature->data[id->signature->length - 2],
1115 ")V"));
1117 va_list args;
1118 jobject result;
1120 va_start (args, id);
1121 result = _Jv_JNI_CallAnyMethodV<jobject, constructor> (env, NULL, klass,
1122 id, args);
1123 va_end (args);
1125 return result;
1128 static jobject JNICALL
1129 _Jv_JNI_NewObjectA (JNIEnv *env, jclass klass, jmethodID id,
1130 jvalue *args)
1132 JvAssert (klass && ! klass->isArray ());
1133 JvAssert (! strcmp (id->name->data, "<init>")
1134 && id->signature->length > 2
1135 && id->signature->data[0] == '('
1136 && ! strcmp (&id->signature->data[id->signature->length - 2],
1137 ")V"));
1139 return _Jv_JNI_CallAnyMethodA<jobject, constructor> (env, NULL, klass,
1140 id, args);
1145 template<typename T>
1146 static T JNICALL
1147 _Jv_JNI_GetField (JNIEnv *env, jobject obj, jfieldID field)
1149 obj = unwrap (obj);
1150 JvAssert (obj);
1151 T *ptr = (T *) ((char *) obj + field->getOffset ());
1152 return wrap_value (env, *ptr);
1155 template<typename T>
1156 static void JNICALL
1157 _Jv_JNI_SetField (JNIEnv *, jobject obj, jfieldID field, T value)
1159 obj = unwrap (obj);
1160 value = unwrap (value);
1162 JvAssert (obj);
1163 T *ptr = (T *) ((char *) obj + field->getOffset ());
1164 *ptr = value;
1167 template<jboolean is_static>
1168 static jfieldID JNICALL
1169 _Jv_JNI_GetAnyFieldID (JNIEnv *env, jclass clazz,
1170 const char *name, const char *sig)
1174 clazz = unwrap (clazz);
1176 _Jv_InitClass (clazz);
1178 _Jv_Utf8Const *a_name = _Jv_makeUtf8Const ((char *) name, -1);
1180 // FIXME: assume that SIG isn't too long.
1181 int len = strlen (sig);
1182 char s[len + 1];
1183 for (int i = 0; i <= len; ++i)
1184 s[i] = (sig[i] == '/') ? '.' : sig[i];
1185 jclass field_class = _Jv_FindClassFromSignature ((char *) s, NULL);
1187 // FIXME: what if field_class == NULL?
1189 java::lang::ClassLoader *loader = clazz->getClassLoaderInternal ();
1190 while (clazz != NULL)
1192 // We acquire the class lock so that fields aren't resolved
1193 // while we are running.
1194 JvSynchronize sync (clazz);
1196 jint count = (is_static
1197 ? JvNumStaticFields (clazz)
1198 : JvNumInstanceFields (clazz));
1199 jfieldID field = (is_static
1200 ? JvGetFirstStaticField (clazz)
1201 : JvGetFirstInstanceField (clazz));
1202 for (jint i = 0; i < count; ++i)
1204 _Jv_Utf8Const *f_name = field->getNameUtf8Const(clazz);
1206 // The field might be resolved or it might not be. It
1207 // is much simpler to always resolve it.
1208 _Jv_Linker::resolve_field (field, loader);
1209 if (_Jv_equalUtf8Consts (f_name, a_name)
1210 && field->getClass() == field_class)
1211 return field;
1213 field = field->getNextField ();
1216 clazz = clazz->getSuperclass ();
1219 env->ex = new java::lang::NoSuchFieldError ();
1221 catch (jthrowable t)
1223 env->ex = t;
1225 return NULL;
1228 template<typename T>
1229 static T JNICALL
1230 _Jv_JNI_GetStaticField (JNIEnv *env, jclass, jfieldID field)
1232 T *ptr = (T *) field->u.addr;
1233 return wrap_value (env, *ptr);
1236 template<typename T>
1237 static void JNICALL
1238 _Jv_JNI_SetStaticField (JNIEnv *, jclass, jfieldID field, T value)
1240 value = unwrap (value);
1241 T *ptr = (T *) field->u.addr;
1242 *ptr = value;
1245 static jstring JNICALL
1246 _Jv_JNI_NewString (JNIEnv *env, const jchar *unichars, jsize len)
1250 jstring r = _Jv_NewString (unichars, len);
1251 return (jstring) wrap_value (env, r);
1253 catch (jthrowable t)
1255 env->ex = t;
1256 return NULL;
1260 static jsize JNICALL
1261 _Jv_JNI_GetStringLength (JNIEnv *, jstring string)
1263 return unwrap (string)->length();
1266 static const jchar * JNICALL
1267 _Jv_JNI_GetStringChars (JNIEnv *, jstring string, jboolean *isCopy)
1269 string = unwrap (string);
1270 jchar *result = _Jv_GetStringChars (string);
1271 mark_for_gc (string, global_ref_table);
1272 if (isCopy)
1273 *isCopy = false;
1274 return (const jchar *) result;
1277 static void JNICALL
1278 _Jv_JNI_ReleaseStringChars (JNIEnv *, jstring string, const jchar *)
1280 unmark_for_gc (unwrap (string), global_ref_table);
1283 static jstring JNICALL
1284 _Jv_JNI_NewStringUTF (JNIEnv *env, const char *bytes)
1288 jstring result = JvNewStringUTF (bytes);
1289 return (jstring) wrap_value (env, result);
1291 catch (jthrowable t)
1293 env->ex = t;
1294 return NULL;
1298 static jsize JNICALL
1299 _Jv_JNI_GetStringUTFLength (JNIEnv *, jstring string)
1301 return JvGetStringUTFLength (unwrap (string));
1304 static const char * JNICALL
1305 _Jv_JNI_GetStringUTFChars (JNIEnv *env, jstring string,
1306 jboolean *isCopy)
1310 string = unwrap (string);
1311 if (string == NULL)
1312 return NULL;
1313 jsize len = JvGetStringUTFLength (string);
1314 char *r = (char *) _Jv_Malloc (len + 1);
1315 JvGetStringUTFRegion (string, 0, string->length(), r);
1316 r[len] = '\0';
1318 if (isCopy)
1319 *isCopy = true;
1321 return (const char *) r;
1323 catch (jthrowable t)
1325 env->ex = t;
1326 return NULL;
1330 static void JNICALL
1331 _Jv_JNI_ReleaseStringUTFChars (JNIEnv *, jstring, const char *utf)
1333 _Jv_Free ((void *) utf);
1336 static void JNICALL
1337 _Jv_JNI_GetStringRegion (JNIEnv *env, jstring string, jsize start,
1338 jsize len, jchar *buf)
1340 string = unwrap (string);
1341 jchar *result = _Jv_GetStringChars (string);
1342 if (start < 0 || start > string->length ()
1343 || len < 0 || start + len > string->length ())
1347 env->ex = new java::lang::StringIndexOutOfBoundsException ();
1349 catch (jthrowable t)
1351 env->ex = t;
1354 else
1355 memcpy (buf, &result[start], len * sizeof (jchar));
1358 static void JNICALL
1359 _Jv_JNI_GetStringUTFRegion (JNIEnv *env, jstring str, jsize start,
1360 jsize len, char *buf)
1362 str = unwrap (str);
1364 if (start < 0 || start > str->length ()
1365 || len < 0 || start + len > str->length ())
1369 env->ex = new java::lang::StringIndexOutOfBoundsException ();
1371 catch (jthrowable t)
1373 env->ex = t;
1376 else
1377 _Jv_GetStringUTFRegion (str, start, len, buf);
1380 static const jchar * JNICALL
1381 _Jv_JNI_GetStringCritical (JNIEnv *, jstring str, jboolean *isCopy)
1383 jchar *result = _Jv_GetStringChars (unwrap (str));
1384 if (isCopy)
1385 *isCopy = false;
1386 return result;
1389 static void JNICALL
1390 _Jv_JNI_ReleaseStringCritical (JNIEnv *, jstring, const jchar *)
1392 // Nothing.
1395 static jsize JNICALL
1396 _Jv_JNI_GetArrayLength (JNIEnv *, jarray array)
1398 return unwrap (array)->length;
1401 static jobjectArray JNICALL
1402 _Jv_JNI_NewObjectArray (JNIEnv *env, jsize length,
1403 jclass elementClass, jobject init)
1407 elementClass = unwrap (elementClass);
1408 init = unwrap (init);
1410 _Jv_CheckCast (elementClass, init);
1411 jarray result = JvNewObjectArray (length, elementClass, init);
1412 return (jobjectArray) wrap_value (env, result);
1414 catch (jthrowable t)
1416 env->ex = t;
1417 return NULL;
1421 static jobject JNICALL
1422 _Jv_JNI_GetObjectArrayElement (JNIEnv *env, jobjectArray array,
1423 jsize index)
1425 if ((unsigned) index >= (unsigned) array->length)
1426 _Jv_ThrowBadArrayIndex (index);
1427 jobject *elts = elements (unwrap (array));
1428 return wrap_value (env, elts[index]);
1431 static void JNICALL
1432 _Jv_JNI_SetObjectArrayElement (JNIEnv *env, jobjectArray array,
1433 jsize index, jobject value)
1437 array = unwrap (array);
1438 value = unwrap (value);
1440 _Jv_CheckArrayStore (array, value);
1441 if ((unsigned) index >= (unsigned) array->length)
1442 _Jv_ThrowBadArrayIndex (index);
1443 jobject *elts = elements (array);
1444 elts[index] = value;
1446 catch (jthrowable t)
1448 env->ex = t;
1452 template<typename T, jclass K>
1453 static JArray<T> * JNICALL
1454 _Jv_JNI_NewPrimitiveArray (JNIEnv *env, jsize length)
1458 return (JArray<T> *) wrap_value (env, _Jv_NewPrimArray (K, length));
1460 catch (jthrowable t)
1462 env->ex = t;
1463 return NULL;
1467 template<typename T, jclass K>
1468 static T * JNICALL
1469 _Jv_JNI_GetPrimitiveArrayElements (JNIEnv *env, JArray<T> *array,
1470 jboolean *isCopy)
1472 array = unwrap (array);
1473 if (! _Jv_JNI_check_types (env, array, K))
1474 return NULL;
1475 T *elts = elements (array);
1476 if (isCopy)
1478 // We elect never to copy.
1479 *isCopy = false;
1481 mark_for_gc (array, global_ref_table);
1482 return elts;
1485 template<typename T, jclass K>
1486 static void JNICALL
1487 _Jv_JNI_ReleasePrimitiveArrayElements (JNIEnv *env, JArray<T> *array,
1488 T *, jint /* mode */)
1490 array = unwrap (array);
1491 _Jv_JNI_check_types (env, array, K);
1492 // Note that we ignore MODE. We can do this because we never copy
1493 // the array elements. My reading of the JNI documentation is that
1494 // this is an option for the implementor.
1495 unmark_for_gc (array, global_ref_table);
1498 template<typename T, jclass K>
1499 static void JNICALL
1500 _Jv_JNI_GetPrimitiveArrayRegion (JNIEnv *env, JArray<T> *array,
1501 jsize start, jsize len,
1502 T *buf)
1504 array = unwrap (array);
1505 if (! _Jv_JNI_check_types (env, array, K))
1506 return;
1508 // The cast to unsigned lets us save a comparison.
1509 if (start < 0 || len < 0
1510 || (unsigned long) (start + len) > (unsigned long) array->length)
1514 // FIXME: index.
1515 env->ex = new java::lang::ArrayIndexOutOfBoundsException ();
1517 catch (jthrowable t)
1519 // Could have thown out of memory error.
1520 env->ex = t;
1523 else
1525 T *elts = elements (array) + start;
1526 memcpy (buf, elts, len * sizeof (T));
1530 template<typename T, jclass K>
1531 static void JNICALL
1532 _Jv_JNI_SetPrimitiveArrayRegion (JNIEnv *env, JArray<T> *array,
1533 jsize start, jsize len, T *buf)
1535 array = unwrap (array);
1536 if (! _Jv_JNI_check_types (env, array, K))
1537 return;
1539 // The cast to unsigned lets us save a comparison.
1540 if (start < 0 || len < 0
1541 || (unsigned long) (start + len) > (unsigned long) array->length)
1545 // FIXME: index.
1546 env->ex = new java::lang::ArrayIndexOutOfBoundsException ();
1548 catch (jthrowable t)
1550 env->ex = t;
1553 else
1555 T *elts = elements (array) + start;
1556 memcpy (elts, buf, len * sizeof (T));
1560 static void * JNICALL
1561 _Jv_JNI_GetPrimitiveArrayCritical (JNIEnv *, jarray array,
1562 jboolean *isCopy)
1564 array = unwrap (array);
1565 // FIXME: does this work?
1566 jclass klass = array->getClass()->getComponentType();
1567 JvAssert (klass->isPrimitive ());
1568 char *r = _Jv_GetArrayElementFromElementType (array, klass);
1569 if (isCopy)
1570 *isCopy = false;
1571 return r;
1574 static void JNICALL
1575 _Jv_JNI_ReleasePrimitiveArrayCritical (JNIEnv *, jarray, void *, jint)
1577 // Nothing.
1580 static jint JNICALL
1581 _Jv_JNI_MonitorEnter (JNIEnv *env, jobject obj)
1585 _Jv_MonitorEnter (unwrap (obj));
1586 return 0;
1588 catch (jthrowable t)
1590 env->ex = t;
1592 return JNI_ERR;
1595 static jint JNICALL
1596 _Jv_JNI_MonitorExit (JNIEnv *env, jobject obj)
1600 _Jv_MonitorExit (unwrap (obj));
1601 return 0;
1603 catch (jthrowable t)
1605 env->ex = t;
1607 return JNI_ERR;
1610 // JDK 1.2
1611 jobject JNICALL
1612 _Jv_JNI_ToReflectedField (JNIEnv *env, jclass cls, jfieldID fieldID,
1613 jboolean)
1617 cls = unwrap (cls);
1618 java::lang::reflect::Field *field = new java::lang::reflect::Field();
1619 field->declaringClass = cls;
1620 field->offset = (char*) fieldID - (char *) cls->fields;
1621 field->name = _Jv_NewStringUtf8Const (fieldID->getNameUtf8Const (cls));
1622 return wrap_value (env, field);
1624 catch (jthrowable t)
1626 env->ex = t;
1628 return NULL;
1631 // JDK 1.2
1632 static jfieldID JNICALL
1633 _Jv_JNI_FromReflectedField (JNIEnv *, jobject f)
1635 using namespace java::lang::reflect;
1637 f = unwrap (f);
1638 Field *field = reinterpret_cast<Field *> (f);
1639 return _Jv_FromReflectedField (field);
1642 jobject JNICALL
1643 _Jv_JNI_ToReflectedMethod (JNIEnv *env, jclass klass, jmethodID id,
1644 jboolean)
1646 using namespace java::lang::reflect;
1648 jobject result = NULL;
1649 klass = unwrap (klass);
1653 if (_Jv_equalUtf8Consts (id->name, init_name))
1655 // A constructor.
1656 Constructor *cons = new Constructor ();
1657 cons->offset = (char *) id - (char *) &klass->methods;
1658 cons->declaringClass = klass;
1659 result = cons;
1661 else
1663 Method *meth = new Method ();
1664 meth->offset = (char *) id - (char *) &klass->methods;
1665 meth->declaringClass = klass;
1666 result = meth;
1669 catch (jthrowable t)
1671 env->ex = t;
1674 return wrap_value (env, result);
1677 static jmethodID JNICALL
1678 _Jv_JNI_FromReflectedMethod (JNIEnv *, jobject method)
1680 using namespace java::lang::reflect;
1681 method = unwrap (method);
1682 if (Method::class$.isInstance (method))
1683 return _Jv_FromReflectedMethod (reinterpret_cast<Method *> (method));
1684 return
1685 _Jv_FromReflectedConstructor (reinterpret_cast<Constructor *> (method));
1688 // JDK 1.2.
1689 jweak JNICALL
1690 _Jv_JNI_NewWeakGlobalRef (JNIEnv *env, jobject obj)
1692 using namespace gnu::gcj::runtime;
1693 JNIWeakRef *ref = NULL;
1697 // This seems weird but I think it is correct.
1698 obj = unwrap (obj);
1699 ref = new JNIWeakRef (obj);
1700 mark_for_gc (ref, global_ref_table);
1702 catch (jthrowable t)
1704 env->ex = t;
1707 return reinterpret_cast<jweak> (ref);
1710 void JNICALL
1711 _Jv_JNI_DeleteWeakGlobalRef (JNIEnv *, jweak obj)
1713 using namespace gnu::gcj::runtime;
1714 JNIWeakRef *ref = reinterpret_cast<JNIWeakRef *> (obj);
1715 unmark_for_gc (ref, global_ref_table);
1716 ref->clear ();
1721 // Direct byte buffers.
1723 static jobject JNICALL
1724 _Jv_JNI_NewDirectByteBuffer (JNIEnv *, void *address, jlong length)
1726 using namespace gnu::gcj;
1727 using namespace java::nio;
1728 return new DirectByteBufferImpl$ReadWrite
1729 (reinterpret_cast<RawData *> (address), length);
1732 static void * JNICALL
1733 _Jv_JNI_GetDirectBufferAddress (JNIEnv *, jobject buffer)
1735 using namespace java::nio;
1736 DirectByteBufferImpl* bb = static_cast<DirectByteBufferImpl *> (buffer);
1737 return reinterpret_cast<void *> (bb->address);
1740 static jlong JNICALL
1741 _Jv_JNI_GetDirectBufferCapacity (JNIEnv *, jobject buffer)
1743 using namespace java::nio;
1744 DirectByteBufferImpl* bb = static_cast<DirectByteBufferImpl *> (buffer);
1745 return bb->capacity();
1750 // Hash table of native methods.
1751 static JNINativeMethod *nathash;
1752 // Number of slots used.
1753 static int nathash_count = 0;
1754 // Number of slots available. Must be power of 2.
1755 static int nathash_size = 0;
1757 #define DELETED_ENTRY ((char *) (~0))
1759 // Compute a hash value for a native method descriptor.
1760 static int
1761 hash (const JNINativeMethod *method)
1763 char *ptr;
1764 int hash = 0;
1766 ptr = method->name;
1767 while (*ptr)
1768 hash = (31 * hash) + *ptr++;
1770 ptr = method->signature;
1771 while (*ptr)
1772 hash = (31 * hash) + *ptr++;
1774 return hash;
1777 // Find the slot where a native method goes.
1778 static JNINativeMethod *
1779 nathash_find_slot (const JNINativeMethod *method)
1781 jint h = hash (method);
1782 int step = (h ^ (h >> 16)) | 1;
1783 int w = h & (nathash_size - 1);
1784 int del = -1;
1786 for (;;)
1788 JNINativeMethod *slotp = &nathash[w];
1789 if (slotp->name == NULL)
1791 if (del >= 0)
1792 return &nathash[del];
1793 else
1794 return slotp;
1796 else if (slotp->name == DELETED_ENTRY)
1797 del = w;
1798 else if (! strcmp (slotp->name, method->name)
1799 && ! strcmp (slotp->signature, method->signature))
1800 return slotp;
1801 w = (w + step) & (nathash_size - 1);
1805 // Find a method. Return NULL if it isn't in the hash table.
1806 static void *
1807 nathash_find (JNINativeMethod *method)
1809 if (nathash == NULL)
1810 return NULL;
1811 JNINativeMethod *slot = nathash_find_slot (method);
1812 if (slot->name == NULL || slot->name == DELETED_ENTRY)
1813 return NULL;
1814 return slot->fnPtr;
1817 static void
1818 natrehash ()
1820 if (nathash == NULL)
1822 nathash_size = 1024;
1823 nathash =
1824 (JNINativeMethod *) _Jv_AllocBytes (nathash_size
1825 * sizeof (JNINativeMethod));
1826 memset (nathash, 0, nathash_size * sizeof (JNINativeMethod));
1828 else
1830 int savesize = nathash_size;
1831 JNINativeMethod *savehash = nathash;
1832 nathash_size *= 2;
1833 nathash =
1834 (JNINativeMethod *) _Jv_AllocBytes (nathash_size
1835 * sizeof (JNINativeMethod));
1836 memset (nathash, 0, nathash_size * sizeof (JNINativeMethod));
1838 for (int i = 0; i < savesize; ++i)
1840 if (savehash[i].name != NULL && savehash[i].name != DELETED_ENTRY)
1842 JNINativeMethod *slot = nathash_find_slot (&savehash[i]);
1843 *slot = savehash[i];
1849 static void
1850 nathash_add (const JNINativeMethod *method)
1852 if (3 * nathash_count >= 2 * nathash_size)
1853 natrehash ();
1854 JNINativeMethod *slot = nathash_find_slot (method);
1855 // If the slot has a real entry in it, then there is no work to do.
1856 if (slot->name != NULL && slot->name != DELETED_ENTRY)
1857 return;
1858 // FIXME
1859 slot->name = strdup (method->name);
1860 slot->signature = strdup (method->signature);
1861 slot->fnPtr = method->fnPtr;
1864 static jint JNICALL
1865 _Jv_JNI_RegisterNatives (JNIEnv *env, jclass klass,
1866 const JNINativeMethod *methods,
1867 jint nMethods)
1869 // Synchronize while we do the work. This must match
1870 // synchronization in some other functions that manipulate or use
1871 // the nathash table.
1872 JvSynchronize sync (global_ref_table);
1874 // Look at each descriptor given us, and find the corresponding
1875 // method in the class.
1876 for (int j = 0; j < nMethods; ++j)
1878 bool found = false;
1880 _Jv_Method *imeths = JvGetFirstMethod (klass);
1881 for (int i = 0; i < JvNumMethods (klass); ++i)
1883 _Jv_Method *self = &imeths[i];
1885 if (! strcmp (self->name->chars (), methods[j].name)
1886 && ! strcmp (self->signature->chars (), methods[j].signature))
1888 if (! (self->accflags & 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 JNICALL
1918 _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->chars ();
1990 const unsigned char *limit = fn + func_name->len ();
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->chars ();
2005 limit = sig + signature->len ();
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, MAYBE_UNUSED int args_size)
2062 int name_length = name->len();
2063 int sig_length = signature->len();
2064 char buf[10 + 6 * (name_length + sig_length) + 12];
2065 int long_start;
2066 void *function;
2068 // Synchronize on something convenient. Right now we use the hash.
2069 JvSynchronize sync (global_ref_table);
2071 // First see if we have an override in the hash table.
2072 strncpy (buf, name->chars (), name_length);
2073 buf[name_length] = '\0';
2074 strncpy (buf + name_length + 1, signature->chars (), sig_length);
2075 buf[name_length + sig_length + 1] = '\0';
2076 JNINativeMethod meth;
2077 meth.name = buf;
2078 meth.signature = buf + name_length + 1;
2079 function = nathash_find (&meth);
2080 if (function != NULL)
2081 return function;
2083 // If there was no override, then look in the symbol table.
2084 buf[0] = '_';
2085 mangled_name (klass, name, signature, buf + 1, &long_start);
2086 char c = buf[long_start + 1];
2087 buf[long_start + 1] = '\0';
2089 function = _Jv_FindSymbolInExecutable (buf + 1);
2090 #ifdef WIN32
2091 // On Win32, we use the "stdcall" calling convention (see JNICALL
2092 // in jni.h).
2094 // For a function named 'fooBar' that takes 'nn' bytes as arguments,
2095 // by default, MinGW GCC exports it as 'fooBar@nn', MSVC exports it
2096 // as '_fooBar@nn' and Borland C exports it as 'fooBar'. We try to
2097 // take care of all these variations here.
2099 char asz_buf[12]; /* '@' + '2147483647' (32-bit INT_MAX) + '\0' */
2100 char long_nm_sv[11]; /* Ditto, except for the '\0'. */
2102 if (function == NULL)
2104 // We have tried searching for the 'fooBar' form (BCC) - now
2105 // try the others.
2107 // First, save the part of the long name that will be damaged
2108 // by appending '@nn'.
2109 memcpy (long_nm_sv, (buf + long_start + 1 + 1), sizeof (long_nm_sv));
2111 sprintf (asz_buf, "@%d", args_size);
2112 strcat (buf, asz_buf);
2114 // Search for the '_fooBar@nn' form (MSVC).
2115 function = _Jv_FindSymbolInExecutable (buf);
2117 if (function == NULL)
2119 // Search for the 'fooBar@nn' form (MinGW GCC).
2120 function = _Jv_FindSymbolInExecutable (buf + 1);
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->chars ());
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 #if FFI_NATIVE_RAW_API
2219 ffi_raw_call (&_this->jni_cif, (void (*)()) _this->function,
2220 ret, real_args);
2221 #else
2222 ffi_java_raw_call (&_this->jni_cif, (void (*)()) _this->function,
2223 ret, real_args);
2224 #endif
2226 if (sync != NULL)
2227 _Jv_MonitorExit (sync);
2229 _Jv_JNI_PopSystemFrame (env);
2232 #endif /* INTERPRETER */
2237 // Invocation API.
2240 // An internal helper function.
2241 static jint
2242 _Jv_JNI_AttachCurrentThread (JavaVM *, jstring name, void **penv,
2243 void *args, jboolean is_daemon)
2245 JavaVMAttachArgs *attach = reinterpret_cast<JavaVMAttachArgs *> (args);
2246 java::lang::ThreadGroup *group = NULL;
2248 if (attach)
2250 // FIXME: do we really want to support 1.1?
2251 if (attach->version != JNI_VERSION_1_4
2252 && attach->version != JNI_VERSION_1_2
2253 && attach->version != JNI_VERSION_1_1)
2254 return JNI_EVERSION;
2256 JvAssert (java::lang::ThreadGroup::class$.isInstance (attach->group));
2257 group = reinterpret_cast<java::lang::ThreadGroup *> (attach->group);
2260 // Attaching an already-attached thread is a no-op.
2261 if (_Jv_GetCurrentJNIEnv () != NULL)
2262 return 0;
2264 JNIEnv *env = (JNIEnv *) _Jv_MallocUnchecked (sizeof (JNIEnv));
2265 if (env == NULL)
2266 return JNI_ERR;
2267 env->p = &_Jv_JNIFunctions;
2268 env->ex = NULL;
2269 env->klass = NULL;
2270 env->locals
2271 = (_Jv_JNI_LocalFrame *) _Jv_MallocUnchecked (sizeof (_Jv_JNI_LocalFrame)
2272 + (FRAME_SIZE
2273 * sizeof (jobject)));
2274 if (env->locals == NULL)
2276 _Jv_Free (env);
2277 return JNI_ERR;
2280 env->locals->marker = MARK_SYSTEM;
2281 env->locals->size = FRAME_SIZE;
2282 env->locals->next = NULL;
2284 for (int i = 0; i < env->locals->size; ++i)
2285 env->locals->vec[i] = NULL;
2287 *penv = reinterpret_cast<void *> (env);
2289 // This thread might already be a Java thread -- this function might
2290 // have been called simply to set the new JNIEnv.
2291 if (_Jv_ThreadCurrent () == NULL)
2295 if (is_daemon)
2296 _Jv_AttachCurrentThreadAsDaemon (name, group);
2297 else
2298 _Jv_AttachCurrentThread (name, group);
2300 catch (jthrowable t)
2302 return JNI_ERR;
2305 _Jv_SetCurrentJNIEnv (env);
2307 return 0;
2310 // This is the one actually used by JNI.
2311 static jint JNICALL
2312 _Jv_JNI_AttachCurrentThread (JavaVM *vm, void **penv, void *args)
2314 return _Jv_JNI_AttachCurrentThread (vm, NULL, penv, args, false);
2317 static jint JNICALL
2318 _Jv_JNI_AttachCurrentThreadAsDaemon (JavaVM *vm, void **penv,
2319 void *args)
2321 return _Jv_JNI_AttachCurrentThread (vm, NULL, penv, args, true);
2324 static jint JNICALL
2325 _Jv_JNI_DestroyJavaVM (JavaVM *vm)
2327 JvAssert (the_vm && vm == the_vm);
2329 JNIEnv *env;
2330 if (_Jv_ThreadCurrent () != NULL)
2332 jstring main_name;
2333 // This sucks.
2336 main_name = JvNewStringLatin1 ("main");
2338 catch (jthrowable t)
2340 return JNI_ERR;
2343 jint r = _Jv_JNI_AttachCurrentThread (vm, main_name,
2344 reinterpret_cast<void **> (&env),
2345 NULL, false);
2346 if (r < 0)
2347 return r;
2349 else
2350 env = _Jv_GetCurrentJNIEnv ();
2352 _Jv_ThreadWait ();
2354 // Docs say that this always returns an error code.
2355 return JNI_ERR;
2358 jint JNICALL
2359 _Jv_JNI_DetachCurrentThread (JavaVM *)
2361 jint code = _Jv_DetachCurrentThread ();
2362 return code ? JNI_EDETACHED : 0;
2365 static jint JNICALL
2366 _Jv_JNI_GetEnv (JavaVM *, void **penv, jint version)
2368 if (_Jv_ThreadCurrent () == NULL)
2370 *penv = NULL;
2371 return JNI_EDETACHED;
2374 #ifdef ENABLE_JVMPI
2375 // Handle JVMPI requests.
2376 if (version == JVMPI_VERSION_1)
2378 *penv = (void *) &_Jv_JVMPI_Interface;
2379 return 0;
2381 #endif
2383 // FIXME: do we really want to support 1.1?
2384 if (version != JNI_VERSION_1_4 && version != JNI_VERSION_1_2
2385 && version != JNI_VERSION_1_1)
2387 *penv = NULL;
2388 return JNI_EVERSION;
2391 *penv = (void *) _Jv_GetCurrentJNIEnv ();
2392 return 0;
2395 jint JNICALL
2396 JNI_GetDefaultJavaVMInitArgs (void *args)
2398 jint version = * (jint *) args;
2399 // Here we only support 1.2 and 1.4.
2400 if (version != JNI_VERSION_1_2 && version != JNI_VERSION_1_4)
2401 return JNI_EVERSION;
2403 JavaVMInitArgs *ia = reinterpret_cast<JavaVMInitArgs *> (args);
2404 ia->version = JNI_VERSION_1_4;
2405 ia->nOptions = 0;
2406 ia->options = NULL;
2407 ia->ignoreUnrecognized = true;
2409 return 0;
2412 jint JNICALL
2413 JNI_CreateJavaVM (JavaVM **vm, void **penv, void *args)
2415 JvAssert (! the_vm);
2417 _Jv_CreateJavaVM (NULL);
2419 // FIXME: synchronize
2420 JavaVM *nvm = (JavaVM *) _Jv_MallocUnchecked (sizeof (JavaVM));
2421 if (nvm == NULL)
2422 return JNI_ERR;
2423 nvm->functions = &_Jv_JNI_InvokeFunctions;
2425 // Parse the arguments.
2426 if (args != NULL)
2428 jint version = * (jint *) args;
2429 // We only support 1.2 and 1.4.
2430 if (version != JNI_VERSION_1_2 && version != JNI_VERSION_1_4)
2431 return JNI_EVERSION;
2432 JavaVMInitArgs *ia = reinterpret_cast<JavaVMInitArgs *> (args);
2433 for (int i = 0; i < ia->nOptions; ++i)
2435 if (! strcmp (ia->options[i].optionString, "vfprintf")
2436 || ! strcmp (ia->options[i].optionString, "exit")
2437 || ! strcmp (ia->options[i].optionString, "abort"))
2439 // We are required to recognize these, but for now we
2440 // don't handle them in any way. FIXME.
2441 continue;
2443 else if (! strncmp (ia->options[i].optionString,
2444 "-verbose", sizeof ("-verbose") - 1))
2446 // We don't do anything with this option either. We
2447 // might want to make sure the argument is valid, but we
2448 // don't really care all that much for now.
2449 continue;
2451 else if (! strncmp (ia->options[i].optionString, "-D", 2))
2453 // FIXME.
2454 continue;
2456 else if (ia->ignoreUnrecognized)
2458 if (ia->options[i].optionString[0] == '_'
2459 || ! strncmp (ia->options[i].optionString, "-X", 2))
2460 continue;
2463 return JNI_ERR;
2467 jint r =_Jv_JNI_AttachCurrentThread (nvm, penv, NULL);
2468 if (r < 0)
2469 return r;
2471 the_vm = nvm;
2472 *vm = the_vm;
2474 return 0;
2477 jint JNICALL
2478 JNI_GetCreatedJavaVMs (JavaVM **vm_buffer, jsize buf_len, jsize *n_vms)
2480 if (buf_len <= 0)
2481 return JNI_ERR;
2483 // We only support a single VM.
2484 if (the_vm != NULL)
2486 vm_buffer[0] = the_vm;
2487 *n_vms = 1;
2489 else
2490 *n_vms = 0;
2491 return 0;
2494 JavaVM *
2495 _Jv_GetJavaVM ()
2497 // FIXME: synchronize
2498 if (! the_vm)
2500 JavaVM *nvm = (JavaVM *) _Jv_MallocUnchecked (sizeof (JavaVM));
2501 if (nvm != NULL)
2502 nvm->functions = &_Jv_JNI_InvokeFunctions;
2503 the_vm = nvm;
2506 // If this is a Java thread, we want to make sure it has an
2507 // associated JNIEnv.
2508 if (_Jv_ThreadCurrent () != NULL)
2510 void *ignore;
2511 _Jv_JNI_AttachCurrentThread (the_vm, &ignore, NULL);
2514 return the_vm;
2517 static jint JNICALL
2518 _Jv_JNI_GetJavaVM (JNIEnv *, JavaVM **vm)
2520 *vm = _Jv_GetJavaVM ();
2521 return *vm == NULL ? JNI_ERR : JNI_OK;
2526 #define RESERVED NULL
2528 struct JNINativeInterface _Jv_JNIFunctions =
2530 RESERVED,
2531 RESERVED,
2532 RESERVED,
2533 RESERVED,
2534 _Jv_JNI_GetVersion, // GetVersion
2535 _Jv_JNI_DefineClass, // DefineClass
2536 _Jv_JNI_FindClass, // FindClass
2537 _Jv_JNI_FromReflectedMethod, // FromReflectedMethod
2538 _Jv_JNI_FromReflectedField, // FromReflectedField
2539 _Jv_JNI_ToReflectedMethod, // ToReflectedMethod
2540 _Jv_JNI_GetSuperclass, // GetSuperclass
2541 _Jv_JNI_IsAssignableFrom, // IsAssignableFrom
2542 _Jv_JNI_ToReflectedField, // ToReflectedField
2543 _Jv_JNI_Throw, // Throw
2544 _Jv_JNI_ThrowNew, // ThrowNew
2545 _Jv_JNI_ExceptionOccurred, // ExceptionOccurred
2546 _Jv_JNI_ExceptionDescribe, // ExceptionDescribe
2547 _Jv_JNI_ExceptionClear, // ExceptionClear
2548 _Jv_JNI_FatalError, // FatalError
2550 _Jv_JNI_PushLocalFrame, // PushLocalFrame
2551 _Jv_JNI_PopLocalFrame, // PopLocalFrame
2552 _Jv_JNI_NewGlobalRef, // NewGlobalRef
2553 _Jv_JNI_DeleteGlobalRef, // DeleteGlobalRef
2554 _Jv_JNI_DeleteLocalRef, // DeleteLocalRef
2556 _Jv_JNI_IsSameObject, // IsSameObject
2558 _Jv_JNI_NewLocalRef, // NewLocalRef
2559 _Jv_JNI_EnsureLocalCapacity, // EnsureLocalCapacity
2561 _Jv_JNI_AllocObject, // AllocObject
2562 _Jv_JNI_NewObject, // NewObject
2563 _Jv_JNI_NewObjectV, // NewObjectV
2564 _Jv_JNI_NewObjectA, // NewObjectA
2565 _Jv_JNI_GetObjectClass, // GetObjectClass
2566 _Jv_JNI_IsInstanceOf, // IsInstanceOf
2567 _Jv_JNI_GetAnyMethodID<false>, // GetMethodID
2569 _Jv_JNI_CallMethod<jobject>, // CallObjectMethod
2570 _Jv_JNI_CallMethodV<jobject>, // CallObjectMethodV
2571 _Jv_JNI_CallMethodA<jobject>, // CallObjectMethodA
2572 _Jv_JNI_CallMethod<jboolean>, // CallBooleanMethod
2573 _Jv_JNI_CallMethodV<jboolean>, // CallBooleanMethodV
2574 _Jv_JNI_CallMethodA<jboolean>, // CallBooleanMethodA
2575 _Jv_JNI_CallMethod<jbyte>, // CallByteMethod
2576 _Jv_JNI_CallMethodV<jbyte>, // CallByteMethodV
2577 _Jv_JNI_CallMethodA<jbyte>, // CallByteMethodA
2578 _Jv_JNI_CallMethod<jchar>, // CallCharMethod
2579 _Jv_JNI_CallMethodV<jchar>, // CallCharMethodV
2580 _Jv_JNI_CallMethodA<jchar>, // CallCharMethodA
2581 _Jv_JNI_CallMethod<jshort>, // CallShortMethod
2582 _Jv_JNI_CallMethodV<jshort>, // CallShortMethodV
2583 _Jv_JNI_CallMethodA<jshort>, // CallShortMethodA
2584 _Jv_JNI_CallMethod<jint>, // CallIntMethod
2585 _Jv_JNI_CallMethodV<jint>, // CallIntMethodV
2586 _Jv_JNI_CallMethodA<jint>, // CallIntMethodA
2587 _Jv_JNI_CallMethod<jlong>, // CallLongMethod
2588 _Jv_JNI_CallMethodV<jlong>, // CallLongMethodV
2589 _Jv_JNI_CallMethodA<jlong>, // CallLongMethodA
2590 _Jv_JNI_CallMethod<jfloat>, // CallFloatMethod
2591 _Jv_JNI_CallMethodV<jfloat>, // CallFloatMethodV
2592 _Jv_JNI_CallMethodA<jfloat>, // CallFloatMethodA
2593 _Jv_JNI_CallMethod<jdouble>, // CallDoubleMethod
2594 _Jv_JNI_CallMethodV<jdouble>, // CallDoubleMethodV
2595 _Jv_JNI_CallMethodA<jdouble>, // CallDoubleMethodA
2596 _Jv_JNI_CallVoidMethod, // CallVoidMethod
2597 _Jv_JNI_CallVoidMethodV, // CallVoidMethodV
2598 _Jv_JNI_CallVoidMethodA, // CallVoidMethodA
2600 // Nonvirtual method invocation functions follow.
2601 _Jv_JNI_CallAnyMethod<jobject, nonvirtual>, // CallNonvirtualObjectMethod
2602 _Jv_JNI_CallAnyMethodV<jobject, nonvirtual>, // CallNonvirtualObjectMethodV
2603 _Jv_JNI_CallAnyMethodA<jobject, nonvirtual>, // CallNonvirtualObjectMethodA
2604 _Jv_JNI_CallAnyMethod<jboolean, nonvirtual>, // CallNonvirtualBooleanMethod
2605 _Jv_JNI_CallAnyMethodV<jboolean, nonvirtual>, // CallNonvirtualBooleanMethodV
2606 _Jv_JNI_CallAnyMethodA<jboolean, nonvirtual>, // CallNonvirtualBooleanMethodA
2607 _Jv_JNI_CallAnyMethod<jbyte, nonvirtual>, // CallNonvirtualByteMethod
2608 _Jv_JNI_CallAnyMethodV<jbyte, nonvirtual>, // CallNonvirtualByteMethodV
2609 _Jv_JNI_CallAnyMethodA<jbyte, nonvirtual>, // CallNonvirtualByteMethodA
2610 _Jv_JNI_CallAnyMethod<jchar, nonvirtual>, // CallNonvirtualCharMethod
2611 _Jv_JNI_CallAnyMethodV<jchar, nonvirtual>, // CallNonvirtualCharMethodV
2612 _Jv_JNI_CallAnyMethodA<jchar, nonvirtual>, // CallNonvirtualCharMethodA
2613 _Jv_JNI_CallAnyMethod<jshort, nonvirtual>, // CallNonvirtualShortMethod
2614 _Jv_JNI_CallAnyMethodV<jshort, nonvirtual>, // CallNonvirtualShortMethodV
2615 _Jv_JNI_CallAnyMethodA<jshort, nonvirtual>, // CallNonvirtualShortMethodA
2616 _Jv_JNI_CallAnyMethod<jint, nonvirtual>, // CallNonvirtualIntMethod
2617 _Jv_JNI_CallAnyMethodV<jint, nonvirtual>, // CallNonvirtualIntMethodV
2618 _Jv_JNI_CallAnyMethodA<jint, nonvirtual>, // CallNonvirtualIntMethodA
2619 _Jv_JNI_CallAnyMethod<jlong, nonvirtual>, // CallNonvirtualLongMethod
2620 _Jv_JNI_CallAnyMethodV<jlong, nonvirtual>, // CallNonvirtualLongMethodV
2621 _Jv_JNI_CallAnyMethodA<jlong, nonvirtual>, // CallNonvirtualLongMethodA
2622 _Jv_JNI_CallAnyMethod<jfloat, nonvirtual>, // CallNonvirtualFloatMethod
2623 _Jv_JNI_CallAnyMethodV<jfloat, nonvirtual>, // CallNonvirtualFloatMethodV
2624 _Jv_JNI_CallAnyMethodA<jfloat, nonvirtual>, // CallNonvirtualFloatMethodA
2625 _Jv_JNI_CallAnyMethod<jdouble, nonvirtual>, // CallNonvirtualDoubleMethod
2626 _Jv_JNI_CallAnyMethodV<jdouble, nonvirtual>, // CallNonvirtualDoubleMethodV
2627 _Jv_JNI_CallAnyMethodA<jdouble, nonvirtual>, // CallNonvirtualDoubleMethodA
2628 _Jv_JNI_CallAnyVoidMethod<nonvirtual>, // CallNonvirtualVoidMethod
2629 _Jv_JNI_CallAnyVoidMethodV<nonvirtual>, // CallNonvirtualVoidMethodV
2630 _Jv_JNI_CallAnyVoidMethodA<nonvirtual>, // CallNonvirtualVoidMethodA
2632 _Jv_JNI_GetAnyFieldID<false>, // GetFieldID
2633 _Jv_JNI_GetField<jobject>, // GetObjectField
2634 _Jv_JNI_GetField<jboolean>, // GetBooleanField
2635 _Jv_JNI_GetField<jbyte>, // GetByteField
2636 _Jv_JNI_GetField<jchar>, // GetCharField
2637 _Jv_JNI_GetField<jshort>, // GetShortField
2638 _Jv_JNI_GetField<jint>, // GetIntField
2639 _Jv_JNI_GetField<jlong>, // GetLongField
2640 _Jv_JNI_GetField<jfloat>, // GetFloatField
2641 _Jv_JNI_GetField<jdouble>, // GetDoubleField
2642 _Jv_JNI_SetField, // SetObjectField
2643 _Jv_JNI_SetField, // SetBooleanField
2644 _Jv_JNI_SetField, // SetByteField
2645 _Jv_JNI_SetField, // SetCharField
2646 _Jv_JNI_SetField, // SetShortField
2647 _Jv_JNI_SetField, // SetIntField
2648 _Jv_JNI_SetField, // SetLongField
2649 _Jv_JNI_SetField, // SetFloatField
2650 _Jv_JNI_SetField, // SetDoubleField
2651 _Jv_JNI_GetAnyMethodID<true>, // GetStaticMethodID
2653 _Jv_JNI_CallStaticMethod<jobject>, // CallStaticObjectMethod
2654 _Jv_JNI_CallStaticMethodV<jobject>, // CallStaticObjectMethodV
2655 _Jv_JNI_CallStaticMethodA<jobject>, // CallStaticObjectMethodA
2656 _Jv_JNI_CallStaticMethod<jboolean>, // CallStaticBooleanMethod
2657 _Jv_JNI_CallStaticMethodV<jboolean>, // CallStaticBooleanMethodV
2658 _Jv_JNI_CallStaticMethodA<jboolean>, // CallStaticBooleanMethodA
2659 _Jv_JNI_CallStaticMethod<jbyte>, // CallStaticByteMethod
2660 _Jv_JNI_CallStaticMethodV<jbyte>, // CallStaticByteMethodV
2661 _Jv_JNI_CallStaticMethodA<jbyte>, // CallStaticByteMethodA
2662 _Jv_JNI_CallStaticMethod<jchar>, // CallStaticCharMethod
2663 _Jv_JNI_CallStaticMethodV<jchar>, // CallStaticCharMethodV
2664 _Jv_JNI_CallStaticMethodA<jchar>, // CallStaticCharMethodA
2665 _Jv_JNI_CallStaticMethod<jshort>, // CallStaticShortMethod
2666 _Jv_JNI_CallStaticMethodV<jshort>, // CallStaticShortMethodV
2667 _Jv_JNI_CallStaticMethodA<jshort>, // CallStaticShortMethodA
2668 _Jv_JNI_CallStaticMethod<jint>, // CallStaticIntMethod
2669 _Jv_JNI_CallStaticMethodV<jint>, // CallStaticIntMethodV
2670 _Jv_JNI_CallStaticMethodA<jint>, // CallStaticIntMethodA
2671 _Jv_JNI_CallStaticMethod<jlong>, // CallStaticLongMethod
2672 _Jv_JNI_CallStaticMethodV<jlong>, // CallStaticLongMethodV
2673 _Jv_JNI_CallStaticMethodA<jlong>, // CallStaticLongMethodA
2674 _Jv_JNI_CallStaticMethod<jfloat>, // CallStaticFloatMethod
2675 _Jv_JNI_CallStaticMethodV<jfloat>, // CallStaticFloatMethodV
2676 _Jv_JNI_CallStaticMethodA<jfloat>, // CallStaticFloatMethodA
2677 _Jv_JNI_CallStaticMethod<jdouble>, // CallStaticDoubleMethod
2678 _Jv_JNI_CallStaticMethodV<jdouble>, // CallStaticDoubleMethodV
2679 _Jv_JNI_CallStaticMethodA<jdouble>, // CallStaticDoubleMethodA
2680 _Jv_JNI_CallStaticVoidMethod, // CallStaticVoidMethod
2681 _Jv_JNI_CallStaticVoidMethodV, // CallStaticVoidMethodV
2682 _Jv_JNI_CallStaticVoidMethodA, // CallStaticVoidMethodA
2684 _Jv_JNI_GetAnyFieldID<true>, // GetStaticFieldID
2685 _Jv_JNI_GetStaticField<jobject>, // GetStaticObjectField
2686 _Jv_JNI_GetStaticField<jboolean>, // GetStaticBooleanField
2687 _Jv_JNI_GetStaticField<jbyte>, // GetStaticByteField
2688 _Jv_JNI_GetStaticField<jchar>, // GetStaticCharField
2689 _Jv_JNI_GetStaticField<jshort>, // GetStaticShortField
2690 _Jv_JNI_GetStaticField<jint>, // GetStaticIntField
2691 _Jv_JNI_GetStaticField<jlong>, // GetStaticLongField
2692 _Jv_JNI_GetStaticField<jfloat>, // GetStaticFloatField
2693 _Jv_JNI_GetStaticField<jdouble>, // GetStaticDoubleField
2694 _Jv_JNI_SetStaticField, // SetStaticObjectField
2695 _Jv_JNI_SetStaticField, // SetStaticBooleanField
2696 _Jv_JNI_SetStaticField, // SetStaticByteField
2697 _Jv_JNI_SetStaticField, // SetStaticCharField
2698 _Jv_JNI_SetStaticField, // SetStaticShortField
2699 _Jv_JNI_SetStaticField, // SetStaticIntField
2700 _Jv_JNI_SetStaticField, // SetStaticLongField
2701 _Jv_JNI_SetStaticField, // SetStaticFloatField
2702 _Jv_JNI_SetStaticField, // SetStaticDoubleField
2703 _Jv_JNI_NewString, // NewString
2704 _Jv_JNI_GetStringLength, // GetStringLength
2705 _Jv_JNI_GetStringChars, // GetStringChars
2706 _Jv_JNI_ReleaseStringChars, // ReleaseStringChars
2707 _Jv_JNI_NewStringUTF, // NewStringUTF
2708 _Jv_JNI_GetStringUTFLength, // GetStringUTFLength
2709 _Jv_JNI_GetStringUTFChars, // GetStringUTFChars
2710 _Jv_JNI_ReleaseStringUTFChars, // ReleaseStringUTFChars
2711 _Jv_JNI_GetArrayLength, // GetArrayLength
2712 _Jv_JNI_NewObjectArray, // NewObjectArray
2713 _Jv_JNI_GetObjectArrayElement, // GetObjectArrayElement
2714 _Jv_JNI_SetObjectArrayElement, // SetObjectArrayElement
2715 _Jv_JNI_NewPrimitiveArray<jboolean, JvPrimClass (boolean)>,
2716 // NewBooleanArray
2717 _Jv_JNI_NewPrimitiveArray<jbyte, JvPrimClass (byte)>, // NewByteArray
2718 _Jv_JNI_NewPrimitiveArray<jchar, JvPrimClass (char)>, // NewCharArray
2719 _Jv_JNI_NewPrimitiveArray<jshort, JvPrimClass (short)>, // NewShortArray
2720 _Jv_JNI_NewPrimitiveArray<jint, JvPrimClass (int)>, // NewIntArray
2721 _Jv_JNI_NewPrimitiveArray<jlong, JvPrimClass (long)>, // NewLongArray
2722 _Jv_JNI_NewPrimitiveArray<jfloat, JvPrimClass (float)>, // NewFloatArray
2723 _Jv_JNI_NewPrimitiveArray<jdouble, JvPrimClass (double)>, // NewDoubleArray
2724 _Jv_JNI_GetPrimitiveArrayElements<jboolean, JvPrimClass (boolean)>,
2725 // GetBooleanArrayElements
2726 _Jv_JNI_GetPrimitiveArrayElements<jbyte, JvPrimClass (byte)>,
2727 // GetByteArrayElements
2728 _Jv_JNI_GetPrimitiveArrayElements<jchar, JvPrimClass (char)>,
2729 // GetCharArrayElements
2730 _Jv_JNI_GetPrimitiveArrayElements<jshort, JvPrimClass (short)>,
2731 // GetShortArrayElements
2732 _Jv_JNI_GetPrimitiveArrayElements<jint, JvPrimClass (int)>,
2733 // GetIntArrayElements
2734 _Jv_JNI_GetPrimitiveArrayElements<jlong, JvPrimClass (long)>,
2735 // GetLongArrayElements
2736 _Jv_JNI_GetPrimitiveArrayElements<jfloat, JvPrimClass (float)>,
2737 // GetFloatArrayElements
2738 _Jv_JNI_GetPrimitiveArrayElements<jdouble, JvPrimClass (double)>,
2739 // GetDoubleArrayElements
2740 _Jv_JNI_ReleasePrimitiveArrayElements<jboolean, JvPrimClass (boolean)>,
2741 // ReleaseBooleanArrayElements
2742 _Jv_JNI_ReleasePrimitiveArrayElements<jbyte, JvPrimClass (byte)>,
2743 // ReleaseByteArrayElements
2744 _Jv_JNI_ReleasePrimitiveArrayElements<jchar, JvPrimClass (char)>,
2745 // ReleaseCharArrayElements
2746 _Jv_JNI_ReleasePrimitiveArrayElements<jshort, JvPrimClass (short)>,
2747 // ReleaseShortArrayElements
2748 _Jv_JNI_ReleasePrimitiveArrayElements<jint, JvPrimClass (int)>,
2749 // ReleaseIntArrayElements
2750 _Jv_JNI_ReleasePrimitiveArrayElements<jlong, JvPrimClass (long)>,
2751 // ReleaseLongArrayElements
2752 _Jv_JNI_ReleasePrimitiveArrayElements<jfloat, JvPrimClass (float)>,
2753 // ReleaseFloatArrayElements
2754 _Jv_JNI_ReleasePrimitiveArrayElements<jdouble, JvPrimClass (double)>,
2755 // ReleaseDoubleArrayElements
2756 _Jv_JNI_GetPrimitiveArrayRegion<jboolean, JvPrimClass (boolean)>,
2757 // GetBooleanArrayRegion
2758 _Jv_JNI_GetPrimitiveArrayRegion<jbyte, JvPrimClass (byte)>,
2759 // GetByteArrayRegion
2760 _Jv_JNI_GetPrimitiveArrayRegion<jchar, JvPrimClass (char)>,
2761 // GetCharArrayRegion
2762 _Jv_JNI_GetPrimitiveArrayRegion<jshort, JvPrimClass (short)>,
2763 // GetShortArrayRegion
2764 _Jv_JNI_GetPrimitiveArrayRegion<jint, JvPrimClass (int)>,
2765 // GetIntArrayRegion
2766 _Jv_JNI_GetPrimitiveArrayRegion<jlong, JvPrimClass (long)>,
2767 // GetLongArrayRegion
2768 _Jv_JNI_GetPrimitiveArrayRegion<jfloat, JvPrimClass (float)>,
2769 // GetFloatArrayRegion
2770 _Jv_JNI_GetPrimitiveArrayRegion<jdouble, JvPrimClass (double)>,
2771 // GetDoubleArrayRegion
2772 _Jv_JNI_SetPrimitiveArrayRegion<jboolean, JvPrimClass (boolean)>,
2773 // SetBooleanArrayRegion
2774 _Jv_JNI_SetPrimitiveArrayRegion<jbyte, JvPrimClass (byte)>,
2775 // SetByteArrayRegion
2776 _Jv_JNI_SetPrimitiveArrayRegion<jchar, JvPrimClass (char)>,
2777 // SetCharArrayRegion
2778 _Jv_JNI_SetPrimitiveArrayRegion<jshort, JvPrimClass (short)>,
2779 // SetShortArrayRegion
2780 _Jv_JNI_SetPrimitiveArrayRegion<jint, JvPrimClass (int)>,
2781 // SetIntArrayRegion
2782 _Jv_JNI_SetPrimitiveArrayRegion<jlong, JvPrimClass (long)>,
2783 // SetLongArrayRegion
2784 _Jv_JNI_SetPrimitiveArrayRegion<jfloat, JvPrimClass (float)>,
2785 // SetFloatArrayRegion
2786 _Jv_JNI_SetPrimitiveArrayRegion<jdouble, JvPrimClass (double)>,
2787 // SetDoubleArrayRegion
2788 _Jv_JNI_RegisterNatives, // RegisterNatives
2789 _Jv_JNI_UnregisterNatives, // UnregisterNatives
2790 _Jv_JNI_MonitorEnter, // MonitorEnter
2791 _Jv_JNI_MonitorExit, // MonitorExit
2792 _Jv_JNI_GetJavaVM, // GetJavaVM
2794 _Jv_JNI_GetStringRegion, // GetStringRegion
2795 _Jv_JNI_GetStringUTFRegion, // GetStringUTFRegion
2796 _Jv_JNI_GetPrimitiveArrayCritical, // GetPrimitiveArrayCritical
2797 _Jv_JNI_ReleasePrimitiveArrayCritical, // ReleasePrimitiveArrayCritical
2798 _Jv_JNI_GetStringCritical, // GetStringCritical
2799 _Jv_JNI_ReleaseStringCritical, // ReleaseStringCritical
2801 _Jv_JNI_NewWeakGlobalRef, // NewWeakGlobalRef
2802 _Jv_JNI_DeleteWeakGlobalRef, // DeleteWeakGlobalRef
2804 _Jv_JNI_ExceptionCheck, // ExceptionCheck
2806 _Jv_JNI_NewDirectByteBuffer, // NewDirectByteBuffer
2807 _Jv_JNI_GetDirectBufferAddress, // GetDirectBufferAddress
2808 _Jv_JNI_GetDirectBufferCapacity // GetDirectBufferCapacity
2811 struct JNIInvokeInterface _Jv_JNI_InvokeFunctions =
2813 RESERVED,
2814 RESERVED,
2815 RESERVED,
2817 _Jv_JNI_DestroyJavaVM,
2818 _Jv_JNI_AttachCurrentThread,
2819 _Jv_JNI_DetachCurrentThread,
2820 _Jv_JNI_GetEnv,
2821 _Jv_JNI_AttachCurrentThreadAsDaemon