OSDN Git Service

* configure.in (--enable-checking): Add fold category.
[pf3gnuchains/gcc-fork.git] / libjava / jni.cc
1 // jni.cc - JNI implementation, including the jump table.
2
3 /* Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003  Free Software Foundation
4
5    This file is part of libgcj.
6
7 This software is copyrighted work licensed under the terms of the
8 Libgcj License.  Please consult the file "LIBGCJ_LICENSE" for
9 details.  */
10
11 #include <config.h>
12
13 #include <stdio.h>
14 #include <stddef.h>
15 #include <string.h>
16
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
24
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>
45
46 #include <gcj/method.h>
47 #include <gcj/field.h>
48
49 #include <java-interp.h>
50 #include <java-threads.h>
51
52 using namespace gcj;
53
54 // This enum is used to select different template instantiations in
55 // the invocation code.
56 enum invocation_type
57 {
58   normal,
59   nonvirtual,
60   static_type,
61   constructor
62 };
63
64 // Forward declarations.
65 extern struct JNINativeInterface _Jv_JNIFunctions;
66 extern struct JNIInvokeInterface _Jv_JNI_InvokeFunctions;
67
68 // Number of slots in the default frame.  The VM must allow at least
69 // 16.
70 #define FRAME_SIZE 32
71
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
78
79 // This structure is used to keep track of local references.
80 struct _Jv_JNI_LocalFrame
81 {
82   // This is true if this frame object represents a pushed frame (eg
83   // from PushLocalFrame).
84   int marker :  2;
85
86   // Number of elements in frame.
87   int size   : 30;
88
89   // Next frame in chain.
90   _Jv_JNI_LocalFrame *next;
91
92   // The elements.  These are allocated using the C "struct hack".
93   jobject vec[0];
94 };
95
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;
100
101 // The only VM.
102 static JavaVM *the_vm;
103
104 #ifdef ENABLE_JVMPI
105 // The only JVMPI interface description.
106 static JVMPI_Interface _Jv_JVMPI_Interface;
107
108 static jint
109 jvmpiEnableEvent (jint event_type, void *)
110 {
111   switch (event_type)
112     {
113     case JVMPI_EVENT_OBJECT_ALLOC:
114       _Jv_JVMPI_Notify_OBJECT_ALLOC = _Jv_JVMPI_Interface.NotifyEvent;
115       break;
116
117     case JVMPI_EVENT_THREAD_START:
118       _Jv_JVMPI_Notify_THREAD_START = _Jv_JVMPI_Interface.NotifyEvent;
119       break;
120
121     case JVMPI_EVENT_THREAD_END:
122       _Jv_JVMPI_Notify_THREAD_END = _Jv_JVMPI_Interface.NotifyEvent;
123       break;
124
125     default:
126       return JVMPI_NOT_AVAILABLE;
127     }
128
129   return JVMPI_SUCCESS;
130 }
131
132 static jint
133 jvmpiDisableEvent (jint event_type, void *)
134 {
135   switch (event_type)
136     {
137     case JVMPI_EVENT_OBJECT_ALLOC:
138       _Jv_JVMPI_Notify_OBJECT_ALLOC = NULL;
139       break;
140
141     default:
142       return JVMPI_NOT_AVAILABLE;
143     }
144
145   return JVMPI_SUCCESS;
146 }
147 #endif
148
149 \f
150
151 void
152 _Jv_JNI_Init (void)
153 {
154   local_ref_table = new java::util::IdentityHashMap;
155   global_ref_table = new java::util::IdentityHashMap;
156
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
165 }
166
167 // Tell the GC that a certain pointer is live.
168 static void
169 mark_for_gc (jobject obj, java::util::IdentityHashMap *ref_table)
170 {
171   JvSynchronize sync (ref_table);
172
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));
178 }
179
180 // Unmark a pointer.
181 static void
182 unmark_for_gc (jobject obj, java::util::IdentityHashMap *ref_table)
183 {
184   JvSynchronize sync (ref_table);
185
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));
196 }
197
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)
203 {
204   return val;
205 }
206
207 // Unwrap a weak reference, if required.
208 template<typename T>
209 static T *
210 unwrap (T *obj)
211 {
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 ());
219 }
220
221 \f
222
223 static jobject
224 (JNICALL _Jv_JNI_NewGlobalRef) (JNIEnv *, jobject obj)
225 {
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;
230 }
231
232 static void
233 (JNICALL _Jv_JNI_DeleteGlobalRef) (JNIEnv *, jobject obj)
234 {
235   // This seems weird but I think it is correct.
236   obj = unwrap (obj);
237   unmark_for_gc (obj, global_ref_table);
238 }
239
240 static void
241 (JNICALL _Jv_JNI_DeleteLocalRef) (JNIEnv *env, jobject obj)
242 {
243   _Jv_JNI_LocalFrame *frame;
244
245   // This seems weird but I think it is correct.
246   obj = unwrap (obj);
247
248   for (frame = env->locals; frame != NULL; frame = frame->next)
249     {
250       for (int i = 0; i < frame->size; ++i)
251         {
252           if (frame->vec[i] == obj)
253             {
254               frame->vec[i] = NULL;
255               unmark_for_gc (obj, local_ref_table);
256               return;
257             }
258         }
259
260       // Don't go past a marked frame.
261       JvAssert (frame->marker == MARK_NONE);
262     }
263
264   JvAssert (0);
265 }
266
267 static jint
268 (JNICALL _Jv_JNI_EnsureLocalCapacity) (JNIEnv *env, jint size)
269 {
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.
273
274   _Jv_JNI_LocalFrame *frame;
275   try
276     {
277       frame = (_Jv_JNI_LocalFrame *) _Jv_Malloc (sizeof (_Jv_JNI_LocalFrame)
278                                                  + size * sizeof (jobject));
279     }
280   catch (jthrowable t)
281     {
282       env->ex = t;
283       return JNI_ERR;
284     }
285
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;
291
292   return 0;
293 }
294
295 static jint
296 (JNICALL _Jv_JNI_PushLocalFrame) (JNIEnv *env, jint size)
297 {
298   jint r = _Jv_JNI_EnsureLocalCapacity (env, size);
299   if (r < 0)
300     return r;
301
302   // The new frame is on top.
303   env->locals->marker = MARK_USER;
304
305   return 0;
306 }
307
308 static jobject
309 (JNICALL _Jv_JNI_NewLocalRef) (JNIEnv *env, jobject obj)
310 {
311   // This seems weird but I think it is correct.
312   obj = unwrap (obj);
313
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)
318     {
319       for (int i = 0; i < frame->size; ++i)
320         {
321           if (frame->vec[i] == NULL)
322             {
323               set = true;
324               done = true;
325               frame->vec[i] = obj;
326               break;
327             }
328         }
329
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;
334     }
335
336   if (! set)
337     {
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;
343     }
344
345   mark_for_gc (obj, local_ref_table);
346   return obj;
347 }
348
349 static jobject
350 (JNICALL _Jv_JNI_PopLocalFrame) (JNIEnv *env, jobject result, int stop)
351 {
352   _Jv_JNI_LocalFrame *rf = env->locals;
353
354   bool done = false;
355   while (rf != NULL && ! done)
356     {
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);
360
361       // If the frame we just freed is the marker frame, we are done.
362       done = (rf->marker == stop);
363
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)
369         {
370           memset (&rf->vec[0], 0, rf->size * sizeof (jobject));
371           break;
372         }
373
374       _Jv_Free (rf);
375       rf = n;
376     }
377
378   // Update the local frame information.
379   env->locals = rf;
380
381   return result == NULL ? NULL : _Jv_JNI_NewLocalRef (env, result);
382 }
383
384 static jobject
385 (JNICALL _Jv_JNI_PopLocalFrame) (JNIEnv *env, jobject result)
386 {
387   return _Jv_JNI_PopLocalFrame (env, result, MARK_USER);
388 }
389
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)
395 {
396   jclass klass = array->getClass()->getComponentType();
397   if (__builtin_expect (klass != K, false))
398     {
399       env->ex = new java::lang::IllegalAccessError ();
400       return false;
401     }
402   else
403     return true;
404 }
405
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)
410 {
411   _Jv_JNI_PopLocalFrame (env, NULL, MARK_SYSTEM);
412
413   if (env->ex)
414     {
415       jthrowable t = env->ex;
416       env->ex = NULL;
417       throw t;
418     }
419 }
420
421 // This function is used from other template functions.  It wraps the
422 // return value appropriately; we specialize it so that object returns
423 // are turned into local references.
424 template<typename T>
425 static T
426 wrap_value (JNIEnv *, T value)
427 {
428   return value;
429 }
430
431 // This specialization is used for jobject, jclass, jstring, jarray,
432 // etc.
433 template<typename T>
434 static T *
435 wrap_value (JNIEnv *env, T *value)
436 {
437   return (value == NULL
438           ? value
439           : (T *) _Jv_JNI_NewLocalRef (env, (jobject) value));
440 }
441
442 \f
443
444 static jint
445 (JNICALL _Jv_JNI_GetVersion) (JNIEnv *)
446 {
447   return JNI_VERSION_1_4;
448 }
449
450 static jclass
451 (JNICALL _Jv_JNI_DefineClass) (JNIEnv *env, const char *name, jobject loader,
452                                const jbyte *buf, jsize bufLen)
453 {
454   try
455     {
456       loader = unwrap (loader);
457
458       jstring sname = JvNewStringUTF (name);
459       jbyteArray bytes = JvNewByteArray (bufLen);
460
461       jbyte *elts = elements (bytes);
462       memcpy (elts, buf, bufLen * sizeof (jbyte));
463
464       java::lang::ClassLoader *l
465         = reinterpret_cast<java::lang::ClassLoader *> (loader);
466
467       jclass result = l->defineClass (sname, bytes, 0, bufLen);
468       return (jclass) wrap_value (env, result);
469     }
470   catch (jthrowable t)
471     {
472       env->ex = t;
473       return NULL;
474     }
475 }
476
477 static jclass
478 (JNICALL _Jv_JNI_FindClass) (JNIEnv *env, const char *name)
479 {
480   // FIXME: assume that NAME isn't too long.
481   int len = strlen (name);
482   char s[len + 1];
483   for (int i = 0; i <= len; ++i)
484     s[i] = (name[i] == '/') ? '.' : name[i];
485
486   jclass r = NULL;
487   try
488     {
489       // This might throw an out of memory exception.
490       jstring n = JvNewStringUTF (s);
491
492       java::lang::ClassLoader *loader = NULL;
493       if (env->klass != NULL)
494         loader = env->klass->getClassLoaderInternal ();
495
496       if (loader == NULL)
497         {
498           // FIXME: should use getBaseClassLoader, but we don't have that
499           // yet.
500           loader = java::lang::ClassLoader::getSystemClassLoader ();
501         }
502
503       r = loader->loadClass (n);
504     }
505   catch (jthrowable t)
506     {
507       env->ex = t;
508     }
509
510   return (jclass) wrap_value (env, r);
511 }
512
513 static jclass
514 (JNICALL _Jv_JNI_GetSuperclass) (JNIEnv *env, jclass clazz)
515 {
516   return (jclass) wrap_value (env, unwrap (clazz)->getSuperclass ());
517 }
518
519 static jboolean
520 (JNICALL _Jv_JNI_IsAssignableFrom) (JNIEnv *, jclass clazz1, jclass clazz2)
521 {
522   return unwrap (clazz1)->isAssignableFrom (unwrap (clazz2));
523 }
524
525 static jint
526 (JNICALL _Jv_JNI_Throw) (JNIEnv *env, jthrowable obj)
527 {
528   // We check in case the user did some funky cast.
529   obj = unwrap (obj);
530   JvAssert (obj != NULL && java::lang::Throwable::class$.isInstance (obj));
531   env->ex = obj;
532   return 0;
533 }
534
535 static jint
536 (JNICALL _Jv_JNI_ThrowNew) (JNIEnv *env, jclass clazz, const char *message)
537 {
538   using namespace java::lang::reflect;
539
540   clazz = unwrap (clazz);
541   JvAssert (java::lang::Throwable::class$.isAssignableFrom (clazz));
542
543   int r = JNI_OK;
544   try
545     {
546       JArray<jclass> *argtypes
547         = (JArray<jclass> *) JvNewObjectArray (1, &java::lang::Class::class$,
548                                                NULL);
549
550       jclass *elts = elements (argtypes);
551       elts[0] = &StringClass;
552
553       Constructor *cons = clazz->getConstructor (argtypes);
554
555       jobjectArray values = JvNewObjectArray (1, &StringClass, NULL);
556       jobject *velts = elements (values);
557       velts[0] = JvNewStringUTF (message);
558
559       jobject obj = cons->newInstance (values);
560
561       env->ex = reinterpret_cast<jthrowable> (obj);
562     }
563   catch (jthrowable t)
564     {
565       env->ex = t;
566       r = JNI_ERR;
567     }
568
569   return r;
570 }
571
572 static jthrowable
573 (JNICALL _Jv_JNI_ExceptionOccurred) (JNIEnv *env)
574 {
575   return (jthrowable) wrap_value (env, env->ex);
576 }
577
578 static void
579 (JNICALL _Jv_JNI_ExceptionDescribe) (JNIEnv *env)
580 {
581   if (env->ex != NULL)
582     env->ex->printStackTrace();
583 }
584
585 static void
586 (JNICALL _Jv_JNI_ExceptionClear) (JNIEnv *env)
587 {
588   env->ex = NULL;
589 }
590
591 static jboolean
592 (JNICALL _Jv_JNI_ExceptionCheck) (JNIEnv *env)
593 {
594   return env->ex != NULL;
595 }
596
597 static void
598 (JNICALL _Jv_JNI_FatalError) (JNIEnv *, const char *message)
599 {
600   JvFail (message);
601 }
602
603 \f
604
605 static jboolean
606 (JNICALL _Jv_JNI_IsSameObject) (JNIEnv *, jobject obj1, jobject obj2)
607 {
608   return unwrap (obj1) == unwrap (obj2);
609 }
610
611 static jobject
612 (JNICALL _Jv_JNI_AllocObject) (JNIEnv *env, jclass clazz)
613 {
614   jobject obj = NULL;
615   using namespace java::lang::reflect;
616
617   try
618     {
619       clazz = unwrap (clazz);
620       JvAssert (clazz && ! clazz->isArray ());
621       if (clazz->isInterface() || Modifier::isAbstract(clazz->getModifiers()))
622         env->ex = new java::lang::InstantiationException ();
623       else
624         obj = JvAllocObject (clazz);
625     }
626   catch (jthrowable t)
627     {
628       env->ex = t;
629     }
630
631   return wrap_value (env, obj);
632 }
633
634 static jclass
635 (JNICALL _Jv_JNI_GetObjectClass) (JNIEnv *env, jobject obj)
636 {
637   obj = unwrap (obj);
638   JvAssert (obj);
639   return (jclass) wrap_value (env, obj->getClass());
640 }
641
642 static jboolean
643 (JNICALL _Jv_JNI_IsInstanceOf) (JNIEnv *, jobject obj, jclass clazz)
644 {
645   return unwrap (clazz)->isInstance(unwrap (obj));
646 }
647
648 \f
649
650 //
651 // This section concerns method invocation.
652 //
653
654 template<jboolean is_static>
655 static jmethodID
656 (JNICALL _Jv_JNI_GetAnyMethodID) (JNIEnv *env, jclass clazz,
657                                   const char *name, const char *sig)
658 {
659   try
660     {
661       clazz = unwrap (clazz);
662       _Jv_InitClass (clazz);
663
664       _Jv_Utf8Const *name_u = _Jv_makeUtf8Const ((char *) name, -1);
665
666       // FIXME: assume that SIG isn't too long.
667       int len = strlen (sig);
668       char s[len + 1];
669       for (int i = 0; i <= len; ++i)
670         s[i] = (sig[i] == '/') ? '.' : sig[i];
671       _Jv_Utf8Const *sig_u = _Jv_makeUtf8Const ((char *) s, -1);
672
673       JvAssert (! clazz->isPrimitive());
674
675       using namespace java::lang::reflect;
676
677       while (clazz != NULL)
678         {
679           jint count = JvNumMethods (clazz);
680           jmethodID meth = JvGetFirstMethod (clazz);
681
682           for (jint i = 0; i < count; ++i)
683             {
684               if (((is_static && Modifier::isStatic (meth->accflags))
685                    || (! is_static && ! Modifier::isStatic (meth->accflags)))
686                   && _Jv_equalUtf8Consts (meth->name, name_u)
687                   && _Jv_equalUtf8Consts (meth->signature, sig_u))
688                 return meth;
689
690               meth = meth->getNextMethod();
691             }
692
693           clazz = clazz->getSuperclass ();
694         }
695
696       env->ex = new java::lang::NoSuchMethodError ();
697     }
698   catch (jthrowable t)
699     {
700       env->ex = t;
701     }
702
703   return NULL;
704 }
705
706 // This is a helper function which turns a va_list into an array of
707 // `jvalue's.  It needs signature information in order to do its work.
708 // The array of values must already be allocated.
709 static void
710 array_from_valist (jvalue *values, JArray<jclass> *arg_types, va_list vargs)
711 {
712   jclass *arg_elts = elements (arg_types);
713   for (int i = 0; i < arg_types->length; ++i)
714     {
715       // Here we assume that sizeof(int) >= sizeof(jint), because we
716       // use `int' when decoding the varargs.  Likewise for
717       // float, and double.  Also we assume that sizeof(jlong) >=
718       // sizeof(int), i.e. that jlong values are not further
719       // promoted.
720       JvAssert (sizeof (int) >= sizeof (jint));
721       JvAssert (sizeof (jlong) >= sizeof (int));
722       JvAssert (sizeof (double) >= sizeof (jfloat));
723       JvAssert (sizeof (double) >= sizeof (jdouble));
724       if (arg_elts[i] == JvPrimClass (byte))
725         values[i].b = (jbyte) va_arg (vargs, int);
726       else if (arg_elts[i] == JvPrimClass (short))
727         values[i].s = (jshort) va_arg (vargs, int);
728       else if (arg_elts[i] == JvPrimClass (int))
729         values[i].i = (jint) va_arg (vargs, int);
730       else if (arg_elts[i] == JvPrimClass (long))
731         values[i].j = (jlong) va_arg (vargs, jlong);
732       else if (arg_elts[i] == JvPrimClass (float))
733         values[i].f = (jfloat) va_arg (vargs, double);
734       else if (arg_elts[i] == JvPrimClass (double))
735         values[i].d = (jdouble) va_arg (vargs, double);
736       else if (arg_elts[i] == JvPrimClass (boolean))
737         values[i].z = (jboolean) va_arg (vargs, int);
738       else if (arg_elts[i] == JvPrimClass (char))
739         values[i].c = (jchar) va_arg (vargs, int);
740       else
741         {
742           // An object.
743           values[i].l = unwrap (va_arg (vargs, jobject));
744         }
745     }
746 }
747
748 // This can call any sort of method: virtual, "nonvirtual", static, or
749 // constructor.
750 template<typename T, invocation_type style>
751 static T
752 (JNICALL _Jv_JNI_CallAnyMethodV) (JNIEnv *env, jobject obj, jclass klass,
753                                   jmethodID id, va_list vargs)
754 {
755   obj = unwrap (obj);
756   klass = unwrap (klass);
757
758   if (style == normal)
759     id = _Jv_LookupDeclaredMethod (obj->getClass (), id->name, id->signature);
760
761   jclass decl_class = klass ? klass : obj->getClass ();
762   JvAssert (decl_class != NULL);
763
764   jclass return_type;
765   JArray<jclass> *arg_types;
766
767   try
768     {
769       _Jv_GetTypesFromSignature (id, decl_class,
770                                  &arg_types, &return_type);
771
772       jvalue args[arg_types->length];
773       array_from_valist (args, arg_types, vargs);
774
775       // For constructors we need to pass the Class we are instantiating.
776       if (style == constructor)
777         return_type = klass;
778
779       jvalue result;
780       jthrowable ex = _Jv_CallAnyMethodA (obj, return_type, id,
781                                           style == constructor,
782                                           arg_types, args, &result);
783
784       if (ex != NULL)
785         env->ex = ex;
786
787       // We cheat a little here.  FIXME.
788       return wrap_value (env, * (T *) &result);
789     }
790   catch (jthrowable t)
791     {
792       env->ex = t;
793     }
794
795   return wrap_value (env, (T) 0);
796 }
797
798 template<typename T, invocation_type style>
799 static T
800 (JNICALL _Jv_JNI_CallAnyMethod) (JNIEnv *env, jobject obj, jclass klass,
801                                  jmethodID method, ...)
802 {
803   va_list args;
804   T result;
805
806   va_start (args, method);
807   result = _Jv_JNI_CallAnyMethodV<T, style> (env, obj, klass, method, args);
808   va_end (args);
809
810   return result;
811 }
812
813 template<typename T, invocation_type style>
814 static T
815 (JNICALL _Jv_JNI_CallAnyMethodA) (JNIEnv *env, jobject obj, jclass klass,
816                                   jmethodID id, jvalue *args)
817 {
818   obj = unwrap (obj);
819   klass = unwrap (klass);
820
821   if (style == normal)
822     id = _Jv_LookupDeclaredMethod (obj->getClass (), id->name, id->signature);
823
824   jclass decl_class = klass ? klass : obj->getClass ();
825   JvAssert (decl_class != NULL);
826
827   jclass return_type;
828   JArray<jclass> *arg_types;
829   try
830     {
831       _Jv_GetTypesFromSignature (id, decl_class,
832                                  &arg_types, &return_type);
833
834       // For constructors we need to pass the Class we are instantiating.
835       if (style == constructor)
836         return_type = klass;
837
838       // Unwrap arguments as required.  Eww.
839       jclass *type_elts = elements (arg_types);
840       jvalue arg_copy[arg_types->length];
841       for (int i = 0; i < arg_types->length; ++i)
842         {
843           if (type_elts[i]->isPrimitive ())
844             arg_copy[i] = args[i];
845           else
846             arg_copy[i].l = unwrap (args[i].l);
847         }
848
849       jvalue result;
850       jthrowable ex = _Jv_CallAnyMethodA (obj, return_type, id,
851                                           style == constructor,
852                                           arg_types, arg_copy, &result);
853
854       if (ex != NULL)
855         env->ex = ex;
856
857       // We cheat a little here.  FIXME.
858       return wrap_value (env, * (T *) &result);
859     }
860   catch (jthrowable t)
861     {
862       env->ex = t;
863     }
864
865   return wrap_value (env, (T) 0);
866 }
867
868 template<invocation_type style>
869 static void
870 (JNICALL _Jv_JNI_CallAnyVoidMethodV) (JNIEnv *env, jobject obj, jclass klass,
871                                       jmethodID id, va_list vargs)
872 {
873   obj = unwrap (obj);
874   klass = unwrap (klass);
875
876   if (style == normal)
877     id = _Jv_LookupDeclaredMethod (obj->getClass (), id->name, id->signature);
878
879   jclass decl_class = klass ? klass : obj->getClass ();
880   JvAssert (decl_class != NULL);
881
882   jclass return_type;
883   JArray<jclass> *arg_types;
884   try
885     {
886       _Jv_GetTypesFromSignature (id, decl_class,
887                                  &arg_types, &return_type);
888
889       jvalue args[arg_types->length];
890       array_from_valist (args, arg_types, vargs);
891
892       // For constructors we need to pass the Class we are instantiating.
893       if (style == constructor)
894         return_type = klass;
895
896       jthrowable ex = _Jv_CallAnyMethodA (obj, return_type, id,
897                                           style == constructor,
898                                           arg_types, args, NULL);
899
900       if (ex != NULL)
901         env->ex = ex;
902     }
903   catch (jthrowable t)
904     {
905       env->ex = t;
906     }
907 }
908
909 template<invocation_type style>
910 static void
911 (JNICALL _Jv_JNI_CallAnyVoidMethod) (JNIEnv *env, jobject obj, jclass klass,
912                                      jmethodID method, ...)
913 {
914   va_list args;
915
916   va_start (args, method);
917   _Jv_JNI_CallAnyVoidMethodV<style> (env, obj, klass, method, args);
918   va_end (args);
919 }
920
921 template<invocation_type style>
922 static void
923 (JNICALL _Jv_JNI_CallAnyVoidMethodA) (JNIEnv *env, jobject obj, jclass klass,
924                                       jmethodID id, jvalue *args)
925 {
926   if (style == normal)
927     id = _Jv_LookupDeclaredMethod (obj->getClass (), id->name, id->signature);
928
929   jclass decl_class = klass ? klass : obj->getClass ();
930   JvAssert (decl_class != NULL);
931
932   jclass return_type;
933   JArray<jclass> *arg_types;
934   try
935     {
936       _Jv_GetTypesFromSignature (id, decl_class,
937                                  &arg_types, &return_type);
938
939       // Unwrap arguments as required.  Eww.
940       jclass *type_elts = elements (arg_types);
941       jvalue arg_copy[arg_types->length];
942       for (int i = 0; i < arg_types->length; ++i)
943         {
944           if (type_elts[i]->isPrimitive ())
945             arg_copy[i] = args[i];
946           else
947             arg_copy[i].l = unwrap (args[i].l);
948         }
949
950       jthrowable ex = _Jv_CallAnyMethodA (obj, return_type, id,
951                                           style == constructor,
952                                           arg_types, args, NULL);
953
954       if (ex != NULL)
955         env->ex = ex;
956     }
957   catch (jthrowable t)
958     {
959       env->ex = t;
960     }
961 }
962
963 // Functions with this signature are used to implement functions in
964 // the CallMethod family.
965 template<typename T>
966 static T
967 (JNICALL _Jv_JNI_CallMethodV) (JNIEnv *env, jobject obj, 
968                                jmethodID id, va_list args)
969 {
970   return _Jv_JNI_CallAnyMethodV<T, normal> (env, obj, NULL, id, args);
971 }
972
973 // Functions with this signature are used to implement functions in
974 // the CallMethod family.
975 template<typename T>
976 static T
977 (JNICALL _Jv_JNI_CallMethod) (JNIEnv *env, jobject obj, jmethodID id, ...)
978 {
979   va_list args;
980   T result;
981
982   va_start (args, id);
983   result = _Jv_JNI_CallAnyMethodV<T, normal> (env, obj, NULL, id, args);
984   va_end (args);
985
986   return result;
987 }
988
989 // Functions with this signature are used to implement functions in
990 // the CallMethod family.
991 template<typename T>
992 static T
993 (JNICALL _Jv_JNI_CallMethodA) (JNIEnv *env, jobject obj, 
994                                jmethodID id, jvalue *args)
995 {
996   return _Jv_JNI_CallAnyMethodA<T, normal> (env, obj, NULL, id, args);
997 }
998
999 static void
1000 (JNICALL _Jv_JNI_CallVoidMethodV) (JNIEnv *env, jobject obj, 
1001                                    jmethodID id, va_list args)
1002 {
1003   _Jv_JNI_CallAnyVoidMethodV<normal> (env, obj, NULL, id, args);
1004 }
1005
1006 static void
1007 (JNICALL _Jv_JNI_CallVoidMethod) (JNIEnv *env, jobject obj, jmethodID id, ...)
1008 {
1009   va_list args;
1010
1011   va_start (args, id);
1012   _Jv_JNI_CallAnyVoidMethodV<normal> (env, obj, NULL, id, args);
1013   va_end (args);
1014 }
1015
1016 static void
1017 (JNICALL _Jv_JNI_CallVoidMethodA) (JNIEnv *env, jobject obj, 
1018                                    jmethodID id, jvalue *args)
1019 {
1020   _Jv_JNI_CallAnyVoidMethodA<normal> (env, obj, NULL, id, args);
1021 }
1022
1023 // Functions with this signature are used to implement functions in
1024 // the CallStaticMethod family.
1025 template<typename T>
1026 static T
1027 (JNICALL _Jv_JNI_CallStaticMethodV) (JNIEnv *env, jclass klass,
1028                                      jmethodID id, va_list args)
1029 {
1030   JvAssert (((id->accflags) & java::lang::reflect::Modifier::STATIC));
1031   JvAssert (java::lang::Class::class$.isInstance (unwrap (klass)));
1032
1033   return _Jv_JNI_CallAnyMethodV<T, static_type> (env, NULL, klass, id, args);
1034 }
1035
1036 // Functions with this signature are used to implement functions in
1037 // the CallStaticMethod family.
1038 template<typename T>
1039 static T
1040 (JNICALL _Jv_JNI_CallStaticMethod) (JNIEnv *env, jclass klass, 
1041                                     jmethodID id, ...)
1042 {
1043   va_list args;
1044   T result;
1045
1046   JvAssert (((id->accflags) & java::lang::reflect::Modifier::STATIC));
1047   JvAssert (java::lang::Class::class$.isInstance (unwrap (klass)));
1048
1049   va_start (args, id);
1050   result = _Jv_JNI_CallAnyMethodV<T, static_type> (env, NULL, klass,
1051                                                    id, args);
1052   va_end (args);
1053
1054   return result;
1055 }
1056
1057 // Functions with this signature are used to implement functions in
1058 // the CallStaticMethod family.
1059 template<typename T>
1060 static T
1061 (JNICALL _Jv_JNI_CallStaticMethodA) (JNIEnv *env, jclass klass, jmethodID id,
1062                                      jvalue *args)
1063 {
1064   JvAssert (((id->accflags) & java::lang::reflect::Modifier::STATIC));
1065   JvAssert (java::lang::Class::class$.isInstance (unwrap (klass)));
1066
1067   return _Jv_JNI_CallAnyMethodA<T, static_type> (env, NULL, klass, id, args);
1068 }
1069
1070 static void
1071 (JNICALL _Jv_JNI_CallStaticVoidMethodV) (JNIEnv *env, jclass klass, 
1072                                          jmethodID id, va_list args)
1073 {
1074   _Jv_JNI_CallAnyVoidMethodV<static_type> (env, NULL, klass, id, args);
1075 }
1076
1077 static void
1078 (JNICALL _Jv_JNI_CallStaticVoidMethod) (JNIEnv *env, jclass klass, 
1079                                         jmethodID id, ...)
1080 {
1081   va_list args;
1082
1083   va_start (args, id);
1084   _Jv_JNI_CallAnyVoidMethodV<static_type> (env, NULL, klass, id, args);
1085   va_end (args);
1086 }
1087
1088 static void
1089 (JNICALL _Jv_JNI_CallStaticVoidMethodA) (JNIEnv *env, jclass klass, 
1090                                          jmethodID id, jvalue *args)
1091 {
1092   _Jv_JNI_CallAnyVoidMethodA<static_type> (env, NULL, klass, id, args);
1093 }
1094
1095 static jobject
1096 (JNICALL _Jv_JNI_NewObjectV) (JNIEnv *env, jclass klass,
1097                               jmethodID id, va_list args)
1098 {
1099   JvAssert (klass && ! klass->isArray ());
1100   JvAssert (! strcmp (id->name->data, "<init>")
1101             && id->signature->length > 2
1102             && id->signature->data[0] == '('
1103             && ! strcmp (&id->signature->data[id->signature->length - 2],
1104                          ")V"));
1105
1106   return _Jv_JNI_CallAnyMethodV<jobject, constructor> (env, NULL, klass,
1107                                                        id, args);
1108 }
1109
1110 static jobject
1111 (JNICALL _Jv_JNI_NewObject) (JNIEnv *env, jclass klass, jmethodID id, ...)
1112 {
1113   JvAssert (klass && ! klass->isArray ());
1114   JvAssert (! strcmp (id->name->data, "<init>")
1115             && id->signature->length > 2
1116             && id->signature->data[0] == '('
1117             && ! strcmp (&id->signature->data[id->signature->length - 2],
1118                          ")V"));
1119
1120   va_list args;
1121   jobject result;
1122
1123   va_start (args, id);
1124   result = _Jv_JNI_CallAnyMethodV<jobject, constructor> (env, NULL, klass,
1125                                                          id, args);
1126   va_end (args);
1127
1128   return result;
1129 }
1130
1131 static jobject
1132 (JNICALL _Jv_JNI_NewObjectA) (JNIEnv *env, jclass klass, jmethodID id,
1133                               jvalue *args)
1134 {
1135   JvAssert (klass && ! klass->isArray ());
1136   JvAssert (! strcmp (id->name->data, "<init>")
1137             && id->signature->length > 2
1138             && id->signature->data[0] == '('
1139             && ! strcmp (&id->signature->data[id->signature->length - 2],
1140                          ")V"));
1141
1142   return _Jv_JNI_CallAnyMethodA<jobject, constructor> (env, NULL, klass,
1143                                                        id, args);
1144 }
1145
1146 \f
1147
1148 template<typename T>
1149 static T
1150 (JNICALL _Jv_JNI_GetField) (JNIEnv *env, jobject obj, jfieldID field)
1151 {
1152   obj = unwrap (obj);
1153   JvAssert (obj);
1154   T *ptr = (T *) ((char *) obj + field->getOffset ());
1155   return wrap_value (env, *ptr);
1156 }
1157
1158 template<typename T>
1159 static void
1160 (JNICALL _Jv_JNI_SetField) (JNIEnv *, jobject obj, jfieldID field, T value)
1161 {
1162   obj = unwrap (obj);
1163   value = unwrap (value);
1164
1165   JvAssert (obj);
1166   T *ptr = (T *) ((char *) obj + field->getOffset ());
1167   *ptr = value;
1168 }
1169
1170 template<jboolean is_static>
1171 static jfieldID
1172 (JNICALL _Jv_JNI_GetAnyFieldID) (JNIEnv *env, jclass clazz,
1173                                  const char *name, const char *sig)
1174 {
1175   try
1176     {
1177       clazz = unwrap (clazz);
1178
1179       _Jv_InitClass (clazz);
1180
1181       _Jv_Utf8Const *a_name = _Jv_makeUtf8Const ((char *) name, -1);
1182
1183       // FIXME: assume that SIG isn't too long.
1184       int len = strlen (sig);
1185       char s[len + 1];
1186       for (int i = 0; i <= len; ++i)
1187         s[i] = (sig[i] == '/') ? '.' : sig[i];
1188       jclass field_class = _Jv_FindClassFromSignature ((char *) s, NULL);
1189
1190       // FIXME: what if field_class == NULL?
1191
1192       java::lang::ClassLoader *loader = clazz->getClassLoaderInternal ();
1193       while (clazz != NULL)
1194         {
1195           // We acquire the class lock so that fields aren't resolved
1196           // while we are running.
1197           JvSynchronize sync (clazz);
1198
1199           jint count = (is_static
1200                         ? JvNumStaticFields (clazz)
1201                         : JvNumInstanceFields (clazz));
1202           jfieldID field = (is_static
1203                             ? JvGetFirstStaticField (clazz)
1204                             : JvGetFirstInstanceField (clazz));
1205           for (jint i = 0; i < count; ++i)
1206             {
1207               _Jv_Utf8Const *f_name = field->getNameUtf8Const(clazz);
1208
1209               // The field might be resolved or it might not be.  It
1210               // is much simpler to always resolve it.
1211               _Jv_ResolveField (field, loader);
1212               if (_Jv_equalUtf8Consts (f_name, a_name)
1213                   && field->getClass() == field_class)
1214                 return field;
1215
1216               field = field->getNextField ();
1217             }
1218
1219           clazz = clazz->getSuperclass ();
1220         }
1221
1222       env->ex = new java::lang::NoSuchFieldError ();
1223     }
1224   catch (jthrowable t)
1225     {
1226       env->ex = t;
1227     }
1228   return NULL;
1229 }
1230
1231 template<typename T>
1232 static T
1233 (JNICALL _Jv_JNI_GetStaticField) (JNIEnv *env, jclass, jfieldID field)
1234 {
1235   T *ptr = (T *) field->u.addr;
1236   return wrap_value (env, *ptr);
1237 }
1238
1239 template<typename T>
1240 static void
1241 (JNICALL _Jv_JNI_SetStaticField) (JNIEnv *, jclass, jfieldID field, T value)
1242 {
1243   value = unwrap (value);
1244   T *ptr = (T *) field->u.addr;
1245   *ptr = value;
1246 }
1247
1248 static jstring
1249 (JNICALL _Jv_JNI_NewString) (JNIEnv *env, const jchar *unichars, jsize len)
1250 {
1251   try
1252     {
1253       jstring r = _Jv_NewString (unichars, len);
1254       return (jstring) wrap_value (env, r);
1255     }
1256   catch (jthrowable t)
1257     {
1258       env->ex = t;
1259       return NULL;
1260     }
1261 }
1262
1263 static jsize
1264 (JNICALL _Jv_JNI_GetStringLength) (JNIEnv *, jstring string)
1265 {
1266   return unwrap (string)->length();
1267 }
1268
1269 static const jchar *
1270 (JNICALL _Jv_JNI_GetStringChars) (JNIEnv *, jstring string, jboolean *isCopy)
1271 {
1272   string = unwrap (string);
1273   jchar *result = _Jv_GetStringChars (string);
1274   mark_for_gc (string, global_ref_table);
1275   if (isCopy)
1276     *isCopy = false;
1277   return (const jchar *) result;
1278 }
1279
1280 static void
1281 (JNICALL _Jv_JNI_ReleaseStringChars) (JNIEnv *, jstring string, const jchar *)
1282 {
1283   unmark_for_gc (unwrap (string), global_ref_table);
1284 }
1285
1286 static jstring
1287 (JNICALL _Jv_JNI_NewStringUTF) (JNIEnv *env, const char *bytes)
1288 {
1289   try
1290     {
1291       jstring result = JvNewStringUTF (bytes);
1292       return (jstring) wrap_value (env, result);
1293     }
1294   catch (jthrowable t)
1295     {
1296       env->ex = t;
1297       return NULL;
1298     }
1299 }
1300
1301 static jsize
1302 (JNICALL _Jv_JNI_GetStringUTFLength) (JNIEnv *, jstring string)
1303 {
1304   return JvGetStringUTFLength (unwrap (string));
1305 }
1306
1307 static const char *
1308 (JNICALL _Jv_JNI_GetStringUTFChars) (JNIEnv *env, jstring string, 
1309                                      jboolean *isCopy)
1310 {
1311   string = unwrap (string);
1312   jsize len = JvGetStringUTFLength (string);
1313   try
1314     {
1315       char *r = (char *) _Jv_Malloc (len + 1);
1316       JvGetStringUTFRegion (string, 0, len, r);
1317       r[len] = '\0';
1318
1319       if (isCopy)
1320         *isCopy = true;
1321
1322       return (const char *) r;
1323     }
1324   catch (jthrowable t)
1325     {
1326       env->ex = t;
1327       return NULL;
1328     }
1329 }
1330
1331 static void
1332 (JNICALL _Jv_JNI_ReleaseStringUTFChars) (JNIEnv *, jstring, const char *utf)
1333 {
1334   _Jv_Free ((void *) utf);
1335 }
1336
1337 static void
1338 (JNICALL _Jv_JNI_GetStringRegion) (JNIEnv *env, jstring string, jsize start, 
1339                                    jsize len, jchar *buf)
1340 {
1341   string = unwrap (string);
1342   jchar *result = _Jv_GetStringChars (string);
1343   if (start < 0 || start > string->length ()
1344       || len < 0 || start + len > string->length ())
1345     {
1346       try
1347         {
1348           env->ex = new java::lang::StringIndexOutOfBoundsException ();
1349         }
1350       catch (jthrowable t)
1351         {
1352           env->ex = t;
1353         }
1354     }
1355   else
1356     memcpy (buf, &result[start], len * sizeof (jchar));
1357 }
1358
1359 static void
1360 (JNICALL _Jv_JNI_GetStringUTFRegion) (JNIEnv *env, jstring str, jsize start,
1361                                       jsize len, char *buf)
1362 {
1363   str = unwrap (str);
1364     
1365   if (start < 0 || start > str->length ()
1366       || len < 0 || start + len > str->length ())
1367     {
1368       try
1369         {
1370           env->ex = new java::lang::StringIndexOutOfBoundsException ();
1371         }
1372       catch (jthrowable t)
1373         {
1374           env->ex = t;
1375         }
1376     }
1377   else
1378     _Jv_GetStringUTFRegion (str, start, len, buf);
1379 }
1380
1381 static const jchar *
1382 (JNICALL _Jv_JNI_GetStringCritical) (JNIEnv *, jstring str, jboolean *isCopy)
1383 {
1384   jchar *result = _Jv_GetStringChars (unwrap (str));
1385   if (isCopy)
1386     *isCopy = false;
1387   return result;
1388 }
1389
1390 static void
1391 (JNICALL _Jv_JNI_ReleaseStringCritical) (JNIEnv *, jstring, const jchar *)
1392 {
1393   // Nothing.
1394 }
1395
1396 static jsize
1397 (JNICALL _Jv_JNI_GetArrayLength) (JNIEnv *, jarray array)
1398 {
1399   return unwrap (array)->length;
1400 }
1401
1402 static jarray
1403 (JNICALL _Jv_JNI_NewObjectArray) (JNIEnv *env, jsize length, 
1404                                   jclass elementClass, jobject init)
1405 {
1406   try
1407     {
1408       elementClass = unwrap (elementClass);
1409       init = unwrap (init);
1410
1411       _Jv_CheckCast (elementClass, init);
1412       jarray result = JvNewObjectArray (length, elementClass, init);
1413       return (jarray) wrap_value (env, result);
1414     }
1415   catch (jthrowable t)
1416     {
1417       env->ex = t;
1418       return NULL;
1419     }
1420 }
1421
1422 static jobject
1423 (JNICALL _Jv_JNI_GetObjectArrayElement) (JNIEnv *env, jobjectArray array, 
1424                                          jsize index)
1425 {
1426   if ((unsigned) index >= (unsigned) array->length)
1427     _Jv_ThrowBadArrayIndex (index);
1428   jobject *elts = elements (unwrap (array));
1429   return wrap_value (env, elts[index]);
1430 }
1431
1432 static void
1433 (JNICALL _Jv_JNI_SetObjectArrayElement) (JNIEnv *env, jobjectArray array, 
1434                                          jsize index, jobject value)
1435 {
1436   try
1437     {
1438       array = unwrap (array);
1439       value = unwrap (value);
1440
1441       _Jv_CheckArrayStore (array, value);
1442       if ((unsigned) index >= (unsigned) array->length)
1443         _Jv_ThrowBadArrayIndex (index);
1444       jobject *elts = elements (array);
1445       elts[index] = value;
1446     }
1447   catch (jthrowable t)
1448     {
1449       env->ex = t;
1450     }
1451 }
1452
1453 template<typename T, jclass K>
1454 static JArray<T> *
1455 (JNICALL _Jv_JNI_NewPrimitiveArray) (JNIEnv *env, jsize length)
1456 {
1457   try
1458     {
1459       return (JArray<T> *) wrap_value (env, _Jv_NewPrimArray (K, length));
1460     }
1461   catch (jthrowable t)
1462     {
1463       env->ex = t;
1464       return NULL;
1465     }
1466 }
1467
1468 template<typename T, jclass K>
1469 static T *
1470 (JNICALL _Jv_JNI_GetPrimitiveArrayElements) (JNIEnv *env, JArray<T> *array,
1471                                              jboolean *isCopy)
1472 {
1473   array = unwrap (array);
1474   if (! _Jv_JNI_check_types (env, array, K))
1475     return NULL;
1476   T *elts = elements (array);
1477   if (isCopy)
1478     {
1479       // We elect never to copy.
1480       *isCopy = false;
1481     }
1482   mark_for_gc (array, global_ref_table);
1483   return elts;
1484 }
1485
1486 template<typename T, jclass K>
1487 static void
1488 (JNICALL _Jv_JNI_ReleasePrimitiveArrayElements) (JNIEnv *env, JArray<T> *array,
1489                                                  T *, jint /* mode */)
1490 {
1491   array = unwrap (array);
1492   _Jv_JNI_check_types (env, array, K);
1493   // Note that we ignore MODE.  We can do this because we never copy
1494   // the array elements.  My reading of the JNI documentation is that
1495   // this is an option for the implementor.
1496   unmark_for_gc (array, global_ref_table);
1497 }
1498
1499 template<typename T, jclass K>
1500 static void
1501 (JNICALL _Jv_JNI_GetPrimitiveArrayRegion) (JNIEnv *env, JArray<T> *array,
1502                                            jsize start, jsize len,
1503                                  T *buf)
1504 {
1505   array = unwrap (array);
1506   if (! _Jv_JNI_check_types (env, array, K))
1507     return;
1508
1509   // The cast to unsigned lets us save a comparison.
1510   if (start < 0 || len < 0
1511       || (unsigned long) (start + len) > (unsigned long) array->length)
1512     {
1513       try
1514         {
1515           // FIXME: index.
1516           env->ex = new java::lang::ArrayIndexOutOfBoundsException ();
1517         }
1518       catch (jthrowable t)
1519         {
1520           // Could have thown out of memory error.
1521           env->ex = t;
1522         }
1523     }
1524   else
1525     {
1526       T *elts = elements (array) + start;
1527       memcpy (buf, elts, len * sizeof (T));
1528     }
1529 }
1530
1531 template<typename T, jclass K>
1532 static void
1533 (JNICALL _Jv_JNI_SetPrimitiveArrayRegion) (JNIEnv *env, JArray<T> *array,
1534                                            jsize start, jsize len, T *buf)
1535 {
1536   array = unwrap (array);
1537   if (! _Jv_JNI_check_types (env, array, K))
1538     return;
1539
1540   // The cast to unsigned lets us save a comparison.
1541   if (start < 0 || len < 0
1542       || (unsigned long) (start + len) > (unsigned long) array->length)
1543     {
1544       try
1545         {
1546           // FIXME: index.
1547           env->ex = new java::lang::ArrayIndexOutOfBoundsException ();
1548         }
1549       catch (jthrowable t)
1550         {
1551           env->ex = t;
1552         }
1553     }
1554   else
1555     {
1556       T *elts = elements (array) + start;
1557       memcpy (elts, buf, len * sizeof (T));
1558     }
1559 }
1560
1561 static void *
1562 (JNICALL _Jv_JNI_GetPrimitiveArrayCritical) (JNIEnv *, jarray array,
1563                                              jboolean *isCopy)
1564 {
1565   array = unwrap (array);
1566   // FIXME: does this work?
1567   jclass klass = array->getClass()->getComponentType();
1568   JvAssert (klass->isPrimitive ());
1569   char *r = _Jv_GetArrayElementFromElementType (array, klass);
1570   if (isCopy)
1571     *isCopy = false;
1572   return r;
1573 }
1574
1575 static void
1576 (JNICALL _Jv_JNI_ReleasePrimitiveArrayCritical) (JNIEnv *, jarray, void *, jint)
1577 {
1578   // Nothing.
1579 }
1580
1581 static jint
1582 (JNICALL _Jv_JNI_MonitorEnter) (JNIEnv *env, jobject obj)
1583 {
1584   try
1585     {
1586       _Jv_MonitorEnter (unwrap (obj));
1587       return 0;
1588     }
1589   catch (jthrowable t)
1590     {
1591       env->ex = t;
1592     }
1593   return JNI_ERR;
1594 }
1595
1596 static jint
1597 (JNICALL _Jv_JNI_MonitorExit) (JNIEnv *env, jobject obj)
1598 {
1599   try
1600     {
1601       _Jv_MonitorExit (unwrap (obj));
1602       return 0;
1603     }
1604   catch (jthrowable t)
1605     {
1606       env->ex = t;
1607     }
1608   return JNI_ERR;
1609 }
1610
1611 // JDK 1.2
1612 jobject
1613 (JNICALL _Jv_JNI_ToReflectedField) (JNIEnv *env, jclass cls, jfieldID fieldID,
1614                                     jboolean)
1615 {
1616   try
1617     {
1618       cls = unwrap (cls);
1619       java::lang::reflect::Field *field = new java::lang::reflect::Field();
1620       field->declaringClass = cls;
1621       field->offset = (char*) fieldID - (char *) cls->fields;
1622       field->name = _Jv_NewStringUtf8Const (fieldID->getNameUtf8Const (cls));
1623       return wrap_value (env, field);
1624     }
1625   catch (jthrowable t)
1626     {
1627       env->ex = t;
1628     }
1629   return NULL;
1630 }
1631
1632 // JDK 1.2
1633 static jfieldID
1634 (JNICALL _Jv_JNI_FromReflectedField) (JNIEnv *, jobject f)
1635 {
1636   using namespace java::lang::reflect;
1637
1638   f = unwrap (f);
1639   Field *field = reinterpret_cast<Field *> (f);
1640   return _Jv_FromReflectedField (field);
1641 }
1642
1643 jobject
1644 (JNICALL _Jv_JNI_ToReflectedMethod) (JNIEnv *env, jclass klass, jmethodID id,
1645                                      jboolean)
1646 {
1647   using namespace java::lang::reflect;
1648
1649   jobject result = NULL;
1650   klass = unwrap (klass);
1651
1652   try
1653     {
1654       if (_Jv_equalUtf8Consts (id->name, init_name))
1655         {
1656           // A constructor.
1657           Constructor *cons = new Constructor ();
1658           cons->offset = (char *) id - (char *) &klass->methods;
1659           cons->declaringClass = klass;
1660           result = cons;
1661         }
1662       else
1663         {
1664           Method *meth = new Method ();
1665           meth->offset = (char *) id - (char *) &klass->methods;
1666           meth->declaringClass = klass;
1667           result = meth;
1668         }
1669     }
1670   catch (jthrowable t)
1671     {
1672       env->ex = t;
1673     }
1674
1675   return wrap_value (env, result);
1676 }
1677
1678 static jmethodID
1679 (JNICALL _Jv_JNI_FromReflectedMethod) (JNIEnv *, jobject method)
1680 {
1681   using namespace java::lang::reflect;
1682   method = unwrap (method);
1683   if (Method::class$.isInstance (method))
1684     return _Jv_FromReflectedMethod (reinterpret_cast<Method *> (method));
1685   return
1686     _Jv_FromReflectedConstructor (reinterpret_cast<Constructor *> (method));
1687 }
1688
1689 // JDK 1.2.
1690 jweak
1691 (JNICALL _Jv_JNI_NewWeakGlobalRef) (JNIEnv *env, jobject obj)
1692 {
1693   using namespace gnu::gcj::runtime;
1694   JNIWeakRef *ref = NULL;
1695
1696   try
1697     {
1698       // This seems weird but I think it is correct.
1699       obj = unwrap (obj);
1700       ref = new JNIWeakRef (obj);
1701       mark_for_gc (ref, global_ref_table);
1702     }
1703   catch (jthrowable t)
1704     {
1705       env->ex = t;
1706     }
1707
1708   return reinterpret_cast<jweak> (ref);
1709 }
1710
1711 void
1712 (JNICALL _Jv_JNI_DeleteWeakGlobalRef) (JNIEnv *, jweak obj)
1713 {
1714   using namespace gnu::gcj::runtime;
1715   JNIWeakRef *ref = reinterpret_cast<JNIWeakRef *> (obj);
1716   unmark_for_gc (ref, global_ref_table);
1717   ref->clear ();
1718 }
1719
1720 \f
1721
1722 // Direct byte buffers.
1723
1724 static jobject
1725 (JNICALL _Jv_JNI_NewDirectByteBuffer) (JNIEnv *, void *address, jlong length)
1726 {
1727   using namespace gnu::gcj;
1728   using namespace java::nio;
1729   return new DirectByteBufferImpl (reinterpret_cast<RawData *> (address),
1730                                    length);
1731 }
1732
1733 static void *
1734 (JNICALL _Jv_JNI_GetDirectBufferAddress) (JNIEnv *, jobject buffer)
1735 {
1736   using namespace java::nio;
1737   DirectByteBufferImpl* bb = static_cast<DirectByteBufferImpl *> (buffer);
1738   return reinterpret_cast<void *> (bb->address);
1739 }
1740
1741 static jlong
1742 (JNICALL _Jv_JNI_GetDirectBufferCapacity) (JNIEnv *, jobject buffer)
1743 {
1744   using namespace java::nio;
1745   DirectByteBufferImpl* bb = static_cast<DirectByteBufferImpl *> (buffer);
1746   return bb->capacity();
1747 }
1748
1749 \f
1750
1751 // Hash table of native methods.
1752 static JNINativeMethod *nathash;
1753 // Number of slots used.
1754 static int nathash_count = 0;
1755 // Number of slots available.  Must be power of 2.
1756 static int nathash_size = 0;
1757
1758 #define DELETED_ENTRY ((char *) (~0))
1759
1760 // Compute a hash value for a native method descriptor.
1761 static int
1762 hash (const JNINativeMethod *method)
1763 {
1764   char *ptr;
1765   int hash = 0;
1766
1767   ptr = method->name;
1768   while (*ptr)
1769     hash = (31 * hash) + *ptr++;
1770
1771   ptr = method->signature;
1772   while (*ptr)
1773     hash = (31 * hash) + *ptr++;
1774
1775   return hash;
1776 }
1777
1778 // Find the slot where a native method goes.
1779 static JNINativeMethod *
1780 nathash_find_slot (const JNINativeMethod *method)
1781 {
1782   jint h = hash (method);
1783   int step = (h ^ (h >> 16)) | 1;
1784   int w = h & (nathash_size - 1);
1785   int del = -1;
1786
1787   for (;;)
1788     {
1789       JNINativeMethod *slotp = &nathash[w];
1790       if (slotp->name == NULL)
1791         {
1792           if (del >= 0)
1793             return &nathash[del];
1794           else
1795             return slotp;
1796         }
1797       else if (slotp->name == DELETED_ENTRY)
1798         del = w;
1799       else if (! strcmp (slotp->name, method->name)
1800                && ! strcmp (slotp->signature, method->signature))
1801         return slotp;
1802       w = (w + step) & (nathash_size - 1);
1803     }
1804 }
1805
1806 // Find a method.  Return NULL if it isn't in the hash table.
1807 static void *
1808 nathash_find (JNINativeMethod *method)
1809 {
1810   if (nathash == NULL)
1811     return NULL;
1812   JNINativeMethod *slot = nathash_find_slot (method);
1813   if (slot->name == NULL || slot->name == DELETED_ENTRY)
1814     return NULL;
1815   return slot->fnPtr;
1816 }
1817
1818 static void
1819 natrehash ()
1820 {
1821   if (nathash == NULL)
1822     {
1823       nathash_size = 1024;
1824       nathash =
1825         (JNINativeMethod *) _Jv_AllocBytes (nathash_size
1826                                             * sizeof (JNINativeMethod));
1827       memset (nathash, 0, nathash_size * sizeof (JNINativeMethod));
1828     }
1829   else
1830     {
1831       int savesize = nathash_size;
1832       JNINativeMethod *savehash = nathash;
1833       nathash_size *= 2;
1834       nathash =
1835         (JNINativeMethod *) _Jv_AllocBytes (nathash_size
1836                                             * sizeof (JNINativeMethod));
1837       memset (nathash, 0, nathash_size * sizeof (JNINativeMethod));
1838
1839       for (int i = 0; i < savesize; ++i)
1840         {
1841           if (savehash[i].name != NULL && savehash[i].name != DELETED_ENTRY)
1842             {
1843               JNINativeMethod *slot = nathash_find_slot (&savehash[i]);
1844               *slot = savehash[i];
1845             }
1846         }
1847     }
1848 }
1849
1850 static void
1851 nathash_add (const JNINativeMethod *method)
1852 {
1853   if (3 * nathash_count >= 2 * nathash_size)
1854     natrehash ();
1855   JNINativeMethod *slot = nathash_find_slot (method);
1856   // If the slot has a real entry in it, then there is no work to do.
1857   if (slot->name != NULL && slot->name != DELETED_ENTRY)
1858     return;
1859   // FIXME
1860   slot->name = strdup (method->name);
1861   slot->signature = strdup (method->signature);
1862   slot->fnPtr = method->fnPtr;
1863 }
1864
1865 static jint
1866 (JNICALL _Jv_JNI_RegisterNatives) (JNIEnv *env, jclass klass,
1867                                    const JNINativeMethod *methods,
1868                                    jint nMethods)
1869 {
1870   // Synchronize while we do the work.  This must match
1871   // synchronization in some other functions that manipulate or use
1872   // the nathash table.
1873   JvSynchronize sync (global_ref_table);
1874
1875   // Look at each descriptor given us, and find the corresponding
1876   // method in the class.
1877   for (int j = 0; j < nMethods; ++j)
1878     {
1879       bool found = false;
1880
1881       _Jv_Method *imeths = JvGetFirstMethod (klass);
1882       for (int i = 0; i < JvNumMethods (klass); ++i)
1883         {
1884           _Jv_Method *self = &imeths[i];
1885
1886           if (! strcmp (self->name->data, methods[j].name)
1887               && ! strcmp (self->signature->data, methods[j].signature))
1888             {
1889               if (! (self->accflags
1890                      & java::lang::reflect::Modifier::NATIVE))
1891                 break;
1892
1893               // Found a match that is native.
1894               found = true;
1895               nathash_add (&methods[j]);
1896
1897               break;
1898             }
1899         }
1900
1901       if (! found)
1902         {
1903           jstring m = JvNewStringUTF (methods[j].name);
1904           try
1905             {
1906               env->ex =new java::lang::NoSuchMethodError (m);
1907             }
1908           catch (jthrowable t)
1909             {
1910               env->ex = t;
1911             }
1912           return JNI_ERR;
1913         }
1914     }
1915
1916   return JNI_OK;
1917 }
1918
1919 static jint
1920 (JNICALL _Jv_JNI_UnregisterNatives) (JNIEnv *, jclass)
1921 {
1922   // FIXME -- we could implement this.
1923   return JNI_ERR;
1924 }
1925
1926 \f
1927
1928 // Add a character to the buffer, encoding properly.
1929 static void
1930 add_char (char *buf, jchar c, int *here)
1931 {
1932   if (c == '_')
1933     {
1934       buf[(*here)++] = '_';
1935       buf[(*here)++] = '1';
1936     }
1937   else if (c == ';')
1938     {
1939       buf[(*here)++] = '_';
1940       buf[(*here)++] = '2';
1941     }
1942   else if (c == '[')
1943     {
1944       buf[(*here)++] = '_';
1945       buf[(*here)++] = '3';
1946     }
1947
1948   // Also check for `.' here because we might be passed an internal
1949   // qualified class name like `foo.bar'.
1950   else if (c == '/' || c == '.')
1951     buf[(*here)++] = '_';
1952   else if ((c >= '0' && c <= '9')
1953            || (c >= 'a' && c <= 'z')
1954            || (c >= 'A' && c <= 'Z'))
1955     buf[(*here)++] = (char) c;
1956   else
1957     {
1958       // "Unicode" character.
1959       buf[(*here)++] = '_';
1960       buf[(*here)++] = '0';
1961       for (int i = 0; i < 4; ++i)
1962         {
1963           int val = c & 0x0f;
1964           buf[(*here) + 3 - i] = (val > 10) ? ('a' + val - 10) : ('0' + val);
1965           c >>= 4;
1966         }
1967       *here += 4;
1968     }
1969 }
1970
1971 // Compute a mangled name for a native function.  This computes the
1972 // long name, and also returns an index which indicates where a NUL
1973 // can be placed to create the short name.  This function assumes that
1974 // the buffer is large enough for its results.
1975 static void
1976 mangled_name (jclass klass, _Jv_Utf8Const *func_name,
1977               _Jv_Utf8Const *signature, char *buf, int *long_start)
1978 {
1979   strcpy (buf, "Java_");
1980   int here = 5;
1981
1982   // Add fully qualified class name.
1983   jchar *chars = _Jv_GetStringChars (klass->getName ());
1984   jint len = klass->getName ()->length ();
1985   for (int i = 0; i < len; ++i)
1986     add_char (buf, chars[i], &here);
1987
1988   // Don't use add_char because we need a literal `_'.
1989   buf[here++] = '_';
1990
1991   const unsigned char *fn = (const unsigned char *) func_name->data;
1992   const unsigned char *limit = fn + func_name->length;
1993   for (int i = 0; ; ++i)
1994     {
1995       int ch = UTF8_GET (fn, limit);
1996       if (ch < 0)
1997         break;
1998       add_char (buf, ch, &here);
1999     }
2000
2001   // This is where the long signature begins.
2002   *long_start = here;
2003   buf[here++] = '_';
2004   buf[here++] = '_';
2005
2006   const unsigned char *sig = (const unsigned char *) signature->data;
2007   limit = sig + signature->length;
2008   JvAssert (sig[0] == '(');
2009   ++sig;
2010   while (1)
2011     {
2012       int ch = UTF8_GET (sig, limit);
2013       if (ch == ')' || ch < 0)
2014         break;
2015       add_char (buf, ch, &here);
2016     }
2017
2018   buf[here] = '\0';
2019 }
2020
2021 // Return the current thread's JNIEnv; if one does not exist, create
2022 // it.  Also create a new system frame for use.  This is `extern "C"'
2023 // because the compiler calls it.
2024 extern "C" JNIEnv *
2025 _Jv_GetJNIEnvNewFrame (jclass klass)
2026 {
2027   JNIEnv *env = _Jv_GetCurrentJNIEnv ();
2028   if (env == NULL)
2029     {
2030       env = (JNIEnv *) _Jv_MallocUnchecked (sizeof (JNIEnv));
2031       env->p = &_Jv_JNIFunctions;
2032       env->klass = klass;
2033       env->locals = NULL;
2034       // We set env->ex below.
2035
2036       _Jv_SetCurrentJNIEnv (env);
2037     }
2038
2039   _Jv_JNI_LocalFrame *frame
2040     = (_Jv_JNI_LocalFrame *) _Jv_MallocUnchecked (sizeof (_Jv_JNI_LocalFrame)
2041                                                   + (FRAME_SIZE
2042                                                      * sizeof (jobject)));
2043
2044   frame->marker = MARK_SYSTEM;
2045   frame->size = FRAME_SIZE;
2046   frame->next = env->locals;
2047
2048   for (int i = 0; i < frame->size; ++i)
2049     frame->vec[i] = NULL;
2050
2051   env->locals = frame;
2052   env->ex = NULL;
2053
2054   return env;
2055 }
2056
2057 // Return the function which implements a particular JNI method.  If
2058 // we can't find the function, we throw the appropriate exception.
2059 // This is `extern "C"' because the compiler uses it.
2060 extern "C" void *
2061 _Jv_LookupJNIMethod (jclass klass, _Jv_Utf8Const *name,
2062                      _Jv_Utf8Const *signature, int args_size)
2063 {
2064   char buf[10 + 6 * (name->length + signature->length) + 12];
2065   int long_start;
2066   void *function;
2067
2068   // Synchronize on something convenient.  Right now we use the hash.
2069   JvSynchronize sync (global_ref_table);
2070
2071   // First see if we have an override in the hash table.
2072   strncpy (buf, name->data, name->length);
2073   buf[name->length] = '\0';
2074   strncpy (buf + name->length + 1, signature->data, signature->length);
2075   buf[name->length + signature->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;
2082
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';
2088
2089   function = _Jv_FindSymbolInExecutable (buf + 1);
2090 #ifdef WIN32
2091   // On Win32, we use the "stdcall" calling convention (see JNICALL
2092   // in jni.h).
2093   // 
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.
2098
2099   char asz_buf[12];    /* '@' + '2147483647' (32-bit INT_MAX) + '\0' */
2100   char long_nm_sv[11]; /* Ditto, except for the '\0'. */
2101
2102   if (function == NULL)
2103     {
2104       // We have tried searching for the 'fooBar' form (BCC) - now
2105       // try the others.
2106
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));
2110
2111       sprintf (asz_buf, "@%d", args_size);
2112       strcat (buf, asz_buf);
2113
2114       // Search for the '_fooBar@nn' form (MSVC).
2115       function = _Jv_FindSymbolInExecutable (buf);
2116
2117       if (function == NULL)
2118         {
2119           // Search for the 'fooBar@nn' form (MinGW GCC).
2120           function = _Jv_FindSymbolInExecutable (buf + 1);
2121         }
2122     }
2123 #else /* WIN32 */
2124   args_size;  /* Dummy statement to avoid unused parameter warning */
2125 #endif /* ! WIN32 */
2126
2127   if (function == NULL)
2128     {
2129       buf[long_start + 1] = c;
2130 #ifdef WIN32
2131       // Restore the part of the long name that was damaged by 
2132       // appending the '@nn'.
2133       memcpy ((buf + long_start + 1 + 1), long_nm_sv, sizeof (long_nm_sv));
2134 #endif /* WIN32 */
2135       function = _Jv_FindSymbolInExecutable (buf + 1);
2136       if (function == NULL)
2137         {
2138 #ifdef WIN32
2139           strcat (buf, asz_buf);
2140           function = _Jv_FindSymbolInExecutable (buf);
2141           if (function == NULL)
2142             function = _Jv_FindSymbolInExecutable (buf + 1);
2143
2144           if (function == NULL)
2145 #endif /* WIN32 */
2146             {
2147               jstring str = JvNewStringUTF (name->data);
2148               throw new java::lang::UnsatisfiedLinkError (str);
2149             }
2150         }
2151     }
2152
2153   return function;
2154 }
2155
2156 #ifdef INTERPRETER
2157
2158 // This function is the stub which is used to turn an ordinary (CNI)
2159 // method call into a JNI call.
2160 void
2161 _Jv_JNIMethod::call (ffi_cif *, void *ret, ffi_raw *args, void *__this)
2162 {
2163   _Jv_JNIMethod* _this = (_Jv_JNIMethod *) __this;
2164
2165   JNIEnv *env = _Jv_GetJNIEnvNewFrame (_this->defining_class);
2166
2167   // FIXME: we should mark every reference parameter as a local.  For
2168   // now we assume a conservative GC, and we assume that the
2169   // references are on the stack somewhere.
2170
2171   // We cache the value that we find, of course, but if we don't find
2172   // a value we don't cache that fact -- we might subsequently load a
2173   // library which finds the function in question.
2174   {
2175     // Synchronize on a convenient object to ensure sanity in case two
2176     // threads reach this point for the same function at the same
2177     // time.
2178     JvSynchronize sync (global_ref_table);
2179     if (_this->function == NULL)
2180       {
2181         int args_size = sizeof (JNIEnv *) + _this->args_raw_size;
2182
2183         if (_this->self->accflags & java::lang::reflect::Modifier::STATIC)
2184           args_size += sizeof (_this->defining_class);
2185
2186         _this->function = _Jv_LookupJNIMethod (_this->defining_class,
2187                                                _this->self->name,
2188                                                _this->self->signature,
2189                                                args_size);
2190       }
2191   }
2192
2193   JvAssert (_this->args_raw_size % sizeof (ffi_raw) == 0);
2194   ffi_raw real_args[2 + _this->args_raw_size / sizeof (ffi_raw)];
2195   int offset = 0;
2196
2197   // First argument is always the environment pointer.
2198   real_args[offset++].ptr = env;
2199
2200   // For a static method, we pass in the Class.  For non-static
2201   // methods, the `this' argument is already handled.
2202   if ((_this->self->accflags & java::lang::reflect::Modifier::STATIC))
2203     real_args[offset++].ptr = _this->defining_class;
2204
2205   // In libgcj, the callee synchronizes.
2206   jobject sync = NULL;
2207   if ((_this->self->accflags & java::lang::reflect::Modifier::SYNCHRONIZED))
2208     {
2209       if ((_this->self->accflags & java::lang::reflect::Modifier::STATIC))
2210         sync = _this->defining_class;
2211       else
2212         sync = (jobject) args[0].ptr;
2213       _Jv_MonitorEnter (sync);
2214     }
2215
2216   // Copy over passed-in arguments.
2217   memcpy (&real_args[offset], args, _this->args_raw_size);
2218
2219   // The actual call to the JNI function.
2220   ffi_raw_call (&_this->jni_cif, (void (*)()) _this->function,
2221                 ret, real_args);
2222
2223   if (sync != NULL)
2224     _Jv_MonitorExit (sync);
2225
2226   _Jv_JNI_PopSystemFrame (env);
2227 }
2228
2229 #endif /* INTERPRETER */
2230
2231 \f
2232
2233 //
2234 // Invocation API.
2235 //
2236
2237 // An internal helper function.
2238 static jint
2239 _Jv_JNI_AttachCurrentThread (JavaVM *, jstring name, void **penv,
2240                              void *args, jboolean is_daemon)
2241 {
2242   JavaVMAttachArgs *attach = reinterpret_cast<JavaVMAttachArgs *> (args);
2243   java::lang::ThreadGroup *group = NULL;
2244
2245   if (attach)
2246     {
2247       // FIXME: do we really want to support 1.1?
2248       if (attach->version != JNI_VERSION_1_4
2249           && attach->version != JNI_VERSION_1_2
2250           && attach->version != JNI_VERSION_1_1)
2251         return JNI_EVERSION;
2252
2253       JvAssert (java::lang::ThreadGroup::class$.isInstance (attach->group));
2254       group = reinterpret_cast<java::lang::ThreadGroup *> (attach->group);
2255     }
2256
2257   // Attaching an already-attached thread is a no-op.
2258   if (_Jv_GetCurrentJNIEnv () != NULL)
2259     return 0;
2260
2261   JNIEnv *env = (JNIEnv *) _Jv_MallocUnchecked (sizeof (JNIEnv));
2262   if (env == NULL)
2263     return JNI_ERR;
2264   env->p = &_Jv_JNIFunctions;
2265   env->ex = NULL;
2266   env->klass = NULL;
2267   env->locals
2268     = (_Jv_JNI_LocalFrame *) _Jv_MallocUnchecked (sizeof (_Jv_JNI_LocalFrame)
2269                                                   + (FRAME_SIZE
2270                                                      * sizeof (jobject)));
2271   if (env->locals == NULL)
2272     {
2273       _Jv_Free (env);
2274       return JNI_ERR;
2275     }
2276
2277   env->locals->marker = MARK_SYSTEM;
2278   env->locals->size = FRAME_SIZE;
2279   env->locals->next = NULL;
2280
2281   for (int i = 0; i < env->locals->size; ++i)
2282     env->locals->vec[i] = NULL;
2283
2284   *penv = reinterpret_cast<void *> (env);
2285
2286   // This thread might already be a Java thread -- this function might
2287   // have been called simply to set the new JNIEnv.
2288   if (_Jv_ThreadCurrent () == NULL)
2289     {
2290       try
2291         {
2292           if (is_daemon)
2293             _Jv_AttachCurrentThreadAsDaemon (name, group);
2294           else
2295             _Jv_AttachCurrentThread (name, group);
2296         }
2297       catch (jthrowable t)
2298         {
2299           return JNI_ERR;
2300         }
2301     }
2302   _Jv_SetCurrentJNIEnv (env);
2303
2304   return 0;
2305 }
2306
2307 // This is the one actually used by JNI.
2308 static jint
2309 (JNICALL _Jv_JNI_AttachCurrentThread) (JavaVM *vm, void **penv, void *args)
2310 {
2311   return _Jv_JNI_AttachCurrentThread (vm, NULL, penv, args, false);
2312 }
2313
2314 static jint
2315 (JNICALL _Jv_JNI_AttachCurrentThreadAsDaemon) (JavaVM *vm, void **penv, 
2316                                                void *args)
2317 {
2318   return _Jv_JNI_AttachCurrentThread (vm, NULL, penv, args, true);
2319 }
2320
2321 static jint
2322 (JNICALL _Jv_JNI_DestroyJavaVM) (JavaVM *vm)
2323 {
2324   JvAssert (the_vm && vm == the_vm);
2325
2326   JNIEnv *env;
2327   if (_Jv_ThreadCurrent () != NULL)
2328     {
2329       jstring main_name;
2330       // This sucks.
2331       try
2332         {
2333           main_name = JvNewStringLatin1 ("main");
2334         }
2335       catch (jthrowable t)
2336         {
2337           return JNI_ERR;
2338         }
2339
2340       jint r = _Jv_JNI_AttachCurrentThread (vm, main_name,
2341                                             reinterpret_cast<void **> (&env),
2342                                             NULL, false);
2343       if (r < 0)
2344         return r;
2345     }
2346   else
2347     env = _Jv_GetCurrentJNIEnv ();
2348
2349   _Jv_ThreadWait ();
2350
2351   // Docs say that this always returns an error code.
2352   return JNI_ERR;
2353 }
2354
2355 jint
2356 (JNICALL _Jv_JNI_DetachCurrentThread) (JavaVM *)
2357 {
2358   jint code = _Jv_DetachCurrentThread ();
2359   return code  ? JNI_EDETACHED : 0;
2360 }
2361
2362 static jint
2363 (JNICALL _Jv_JNI_GetEnv) (JavaVM *, void **penv, jint version)
2364 {
2365   if (_Jv_ThreadCurrent () == NULL)
2366     {
2367       *penv = NULL;
2368       return JNI_EDETACHED;
2369     }
2370
2371 #ifdef ENABLE_JVMPI
2372   // Handle JVMPI requests.
2373   if (version == JVMPI_VERSION_1)
2374     {
2375       *penv = (void *) &_Jv_JVMPI_Interface;
2376       return 0;
2377     }
2378 #endif
2379
2380   // FIXME: do we really want to support 1.1?
2381   if (version != JNI_VERSION_1_4 && version != JNI_VERSION_1_2
2382       && version != JNI_VERSION_1_1)
2383     {
2384       *penv = NULL;
2385       return JNI_EVERSION;
2386     }
2387
2388   *penv = (void *) _Jv_GetCurrentJNIEnv ();
2389   return 0;
2390 }
2391
2392 JNIEXPORT jint JNICALL
2393 JNI_GetDefaultJavaVMInitArgs (void *args)
2394 {
2395   jint version = * (jint *) args;
2396   // Here we only support 1.2 and 1.4.
2397   if (version != JNI_VERSION_1_2 && version != JNI_VERSION_1_4)
2398     return JNI_EVERSION;
2399
2400   JavaVMInitArgs *ia = reinterpret_cast<JavaVMInitArgs *> (args);
2401   ia->version = JNI_VERSION_1_4;
2402   ia->nOptions = 0;
2403   ia->options = NULL;
2404   ia->ignoreUnrecognized = true;
2405
2406   return 0;
2407 }
2408
2409 JNIEXPORT jint JNICALL
2410 JNI_CreateJavaVM (JavaVM **vm, void **penv, void *args)
2411 {
2412   JvAssert (! the_vm);
2413
2414   _Jv_CreateJavaVM (NULL);
2415
2416   // FIXME: synchronize
2417   JavaVM *nvm = (JavaVM *) _Jv_MallocUnchecked (sizeof (JavaVM));
2418   if (nvm == NULL)
2419     return JNI_ERR;
2420   nvm->functions = &_Jv_JNI_InvokeFunctions;
2421
2422   // Parse the arguments.
2423   if (args != NULL)
2424     {
2425       jint version = * (jint *) args;
2426       // We only support 1.2 and 1.4.
2427       if (version != JNI_VERSION_1_2 && version != JNI_VERSION_1_4)
2428         return JNI_EVERSION;
2429       JavaVMInitArgs *ia = reinterpret_cast<JavaVMInitArgs *> (args);
2430       for (int i = 0; i < ia->nOptions; ++i)
2431         {
2432           if (! strcmp (ia->options[i].optionString, "vfprintf")
2433               || ! strcmp (ia->options[i].optionString, "exit")
2434               || ! strcmp (ia->options[i].optionString, "abort"))
2435             {
2436               // We are required to recognize these, but for now we
2437               // don't handle them in any way.  FIXME.
2438               continue;
2439             }
2440           else if (! strncmp (ia->options[i].optionString,
2441                               "-verbose", sizeof ("-verbose") - 1))
2442             {
2443               // We don't do anything with this option either.  We
2444               // might want to make sure the argument is valid, but we
2445               // don't really care all that much for now.
2446               continue;
2447             }
2448           else if (! strncmp (ia->options[i].optionString, "-D", 2))
2449             {
2450               // FIXME.
2451               continue;
2452             }
2453           else if (ia->ignoreUnrecognized)
2454             {
2455               if (ia->options[i].optionString[0] == '_'
2456                   || ! strncmp (ia->options[i].optionString, "-X", 2))
2457                 continue;
2458             }
2459
2460           return JNI_ERR;
2461         }
2462     }
2463
2464   jint r =_Jv_JNI_AttachCurrentThread (nvm, penv, NULL);
2465   if (r < 0)
2466     return r;
2467
2468   the_vm = nvm;
2469   *vm = the_vm;
2470
2471   return 0;
2472 }
2473
2474 JNIEXPORT jint JNICALL
2475 JNI_GetCreatedJavaVMs (JavaVM **vm_buffer, jsize buf_len, jsize *n_vms)
2476 {
2477   if (buf_len <= 0)
2478     return JNI_ERR;
2479
2480   // We only support a single VM.
2481   if (the_vm != NULL)
2482     {
2483       vm_buffer[0] = the_vm;
2484       *n_vms = 1;
2485     }
2486   else
2487     *n_vms = 0;
2488   return 0;
2489 }
2490
2491 JavaVM *
2492 _Jv_GetJavaVM ()
2493 {
2494   // FIXME: synchronize
2495   if (! the_vm)
2496     {
2497       JavaVM *nvm = (JavaVM *) _Jv_MallocUnchecked (sizeof (JavaVM));
2498       if (nvm != NULL)
2499         nvm->functions = &_Jv_JNI_InvokeFunctions;
2500       the_vm = nvm;
2501     }
2502
2503   // If this is a Java thread, we want to make sure it has an
2504   // associated JNIEnv.
2505   if (_Jv_ThreadCurrent () != NULL)
2506     {
2507       void *ignore;
2508       _Jv_JNI_AttachCurrentThread (the_vm, &ignore, NULL);
2509     }
2510
2511   return the_vm;
2512 }
2513
2514 static jint
2515 (JNICALL _Jv_JNI_GetJavaVM) (JNIEnv *, JavaVM **vm)
2516 {
2517   *vm = _Jv_GetJavaVM ();
2518   return *vm == NULL ? JNI_ERR : JNI_OK;
2519 }
2520
2521 \f
2522
2523 #define RESERVED NULL
2524
2525 struct JNINativeInterface _Jv_JNIFunctions =
2526 {
2527   RESERVED,
2528   RESERVED,
2529   RESERVED,
2530   RESERVED,
2531   _Jv_JNI_GetVersion,           // GetVersion
2532   _Jv_JNI_DefineClass,          // DefineClass
2533   _Jv_JNI_FindClass,            // FindClass
2534   _Jv_JNI_FromReflectedMethod,  // FromReflectedMethod
2535   _Jv_JNI_FromReflectedField,   // FromReflectedField
2536   _Jv_JNI_ToReflectedMethod,    // ToReflectedMethod
2537   _Jv_JNI_GetSuperclass,        // GetSuperclass
2538   _Jv_JNI_IsAssignableFrom,     // IsAssignableFrom
2539   _Jv_JNI_ToReflectedField,     // ToReflectedField
2540   _Jv_JNI_Throw,                // Throw
2541   _Jv_JNI_ThrowNew,             // ThrowNew
2542   _Jv_JNI_ExceptionOccurred,    // ExceptionOccurred
2543   _Jv_JNI_ExceptionDescribe,    // ExceptionDescribe
2544   _Jv_JNI_ExceptionClear,       // ExceptionClear
2545   _Jv_JNI_FatalError,           // FatalError
2546
2547   _Jv_JNI_PushLocalFrame,       // PushLocalFrame
2548   _Jv_JNI_PopLocalFrame,        // PopLocalFrame
2549   _Jv_JNI_NewGlobalRef,         // NewGlobalRef
2550   _Jv_JNI_DeleteGlobalRef,      // DeleteGlobalRef
2551   _Jv_JNI_DeleteLocalRef,       // DeleteLocalRef
2552
2553   _Jv_JNI_IsSameObject,         // IsSameObject
2554
2555   _Jv_JNI_NewLocalRef,          // NewLocalRef
2556   _Jv_JNI_EnsureLocalCapacity,  // EnsureLocalCapacity
2557
2558   _Jv_JNI_AllocObject,              // AllocObject
2559   _Jv_JNI_NewObject,                // NewObject
2560   _Jv_JNI_NewObjectV,               // NewObjectV
2561   _Jv_JNI_NewObjectA,               // NewObjectA
2562   _Jv_JNI_GetObjectClass,           // GetObjectClass
2563   _Jv_JNI_IsInstanceOf,             // IsInstanceOf
2564   _Jv_JNI_GetAnyMethodID<false>,    // GetMethodID
2565
2566   _Jv_JNI_CallMethod<jobject>,          // CallObjectMethod
2567   _Jv_JNI_CallMethodV<jobject>,         // CallObjectMethodV
2568   _Jv_JNI_CallMethodA<jobject>,         // CallObjectMethodA
2569   _Jv_JNI_CallMethod<jboolean>,         // CallBooleanMethod
2570   _Jv_JNI_CallMethodV<jboolean>,        // CallBooleanMethodV
2571   _Jv_JNI_CallMethodA<jboolean>,        // CallBooleanMethodA
2572   _Jv_JNI_CallMethod<jbyte>,            // CallByteMethod
2573   _Jv_JNI_CallMethodV<jbyte>,           // CallByteMethodV
2574   _Jv_JNI_CallMethodA<jbyte>,           // CallByteMethodA
2575   _Jv_JNI_CallMethod<jchar>,            // CallCharMethod
2576   _Jv_JNI_CallMethodV<jchar>,           // CallCharMethodV
2577   _Jv_JNI_CallMethodA<jchar>,           // CallCharMethodA
2578   _Jv_JNI_CallMethod<jshort>,           // CallShortMethod
2579   _Jv_JNI_CallMethodV<jshort>,          // CallShortMethodV
2580   _Jv_JNI_CallMethodA<jshort>,          // CallShortMethodA
2581   _Jv_JNI_CallMethod<jint>,             // CallIntMethod
2582   _Jv_JNI_CallMethodV<jint>,            // CallIntMethodV
2583   _Jv_JNI_CallMethodA<jint>,            // CallIntMethodA
2584   _Jv_JNI_CallMethod<jlong>,            // CallLongMethod
2585   _Jv_JNI_CallMethodV<jlong>,           // CallLongMethodV
2586   _Jv_JNI_CallMethodA<jlong>,           // CallLongMethodA
2587   _Jv_JNI_CallMethod<jfloat>,           // CallFloatMethod
2588   _Jv_JNI_CallMethodV<jfloat>,          // CallFloatMethodV
2589   _Jv_JNI_CallMethodA<jfloat>,          // CallFloatMethodA
2590   _Jv_JNI_CallMethod<jdouble>,          // CallDoubleMethod
2591   _Jv_JNI_CallMethodV<jdouble>,         // CallDoubleMethodV
2592   _Jv_JNI_CallMethodA<jdouble>,         // CallDoubleMethodA
2593   _Jv_JNI_CallVoidMethod,               // CallVoidMethod
2594   _Jv_JNI_CallVoidMethodV,              // CallVoidMethodV
2595   _Jv_JNI_CallVoidMethodA,              // CallVoidMethodA
2596
2597   // Nonvirtual method invocation functions follow.
2598   _Jv_JNI_CallAnyMethod<jobject, nonvirtual>,   // CallNonvirtualObjectMethod
2599   _Jv_JNI_CallAnyMethodV<jobject, nonvirtual>,  // CallNonvirtualObjectMethodV
2600   _Jv_JNI_CallAnyMethodA<jobject, nonvirtual>,  // CallNonvirtualObjectMethodA
2601   _Jv_JNI_CallAnyMethod<jboolean, nonvirtual>,  // CallNonvirtualBooleanMethod
2602   _Jv_JNI_CallAnyMethodV<jboolean, nonvirtual>, // CallNonvirtualBooleanMethodV
2603   _Jv_JNI_CallAnyMethodA<jboolean, nonvirtual>, // CallNonvirtualBooleanMethodA
2604   _Jv_JNI_CallAnyMethod<jbyte, nonvirtual>,     // CallNonvirtualByteMethod
2605   _Jv_JNI_CallAnyMethodV<jbyte, nonvirtual>,    // CallNonvirtualByteMethodV
2606   _Jv_JNI_CallAnyMethodA<jbyte, nonvirtual>,    // CallNonvirtualByteMethodA
2607   _Jv_JNI_CallAnyMethod<jchar, nonvirtual>,     // CallNonvirtualCharMethod
2608   _Jv_JNI_CallAnyMethodV<jchar, nonvirtual>,    // CallNonvirtualCharMethodV
2609   _Jv_JNI_CallAnyMethodA<jchar, nonvirtual>,    // CallNonvirtualCharMethodA
2610   _Jv_JNI_CallAnyMethod<jshort, nonvirtual>,    // CallNonvirtualShortMethod
2611   _Jv_JNI_CallAnyMethodV<jshort, nonvirtual>,   // CallNonvirtualShortMethodV
2612   _Jv_JNI_CallAnyMethodA<jshort, nonvirtual>,   // CallNonvirtualShortMethodA
2613   _Jv_JNI_CallAnyMethod<jint, nonvirtual>,      // CallNonvirtualIntMethod
2614   _Jv_JNI_CallAnyMethodV<jint, nonvirtual>,     // CallNonvirtualIntMethodV
2615   _Jv_JNI_CallAnyMethodA<jint, nonvirtual>,     // CallNonvirtualIntMethodA
2616   _Jv_JNI_CallAnyMethod<jlong, nonvirtual>,     // CallNonvirtualLongMethod
2617   _Jv_JNI_CallAnyMethodV<jlong, nonvirtual>,    // CallNonvirtualLongMethodV
2618   _Jv_JNI_CallAnyMethodA<jlong, nonvirtual>,    // CallNonvirtualLongMethodA
2619   _Jv_JNI_CallAnyMethod<jfloat, nonvirtual>,    // CallNonvirtualFloatMethod
2620   _Jv_JNI_CallAnyMethodV<jfloat, nonvirtual>,   // CallNonvirtualFloatMethodV
2621   _Jv_JNI_CallAnyMethodA<jfloat, nonvirtual>,   // CallNonvirtualFloatMethodA
2622   _Jv_JNI_CallAnyMethod<jdouble, nonvirtual>,   // CallNonvirtualDoubleMethod
2623   _Jv_JNI_CallAnyMethodV<jdouble, nonvirtual>,  // CallNonvirtualDoubleMethodV
2624   _Jv_JNI_CallAnyMethodA<jdouble, nonvirtual>,  // CallNonvirtualDoubleMethodA
2625   _Jv_JNI_CallAnyVoidMethod<nonvirtual>,        // CallNonvirtualVoidMethod
2626   _Jv_JNI_CallAnyVoidMethodV<nonvirtual>,       // CallNonvirtualVoidMethodV
2627   _Jv_JNI_CallAnyVoidMethodA<nonvirtual>,       // CallNonvirtualVoidMethodA
2628
2629   _Jv_JNI_GetAnyFieldID<false>, // GetFieldID
2630   _Jv_JNI_GetField<jobject>,    // GetObjectField
2631   _Jv_JNI_GetField<jboolean>,   // GetBooleanField
2632   _Jv_JNI_GetField<jbyte>,      // GetByteField
2633   _Jv_JNI_GetField<jchar>,      // GetCharField
2634   _Jv_JNI_GetField<jshort>,     // GetShortField
2635   _Jv_JNI_GetField<jint>,       // GetIntField
2636   _Jv_JNI_GetField<jlong>,      // GetLongField
2637   _Jv_JNI_GetField<jfloat>,     // GetFloatField
2638   _Jv_JNI_GetField<jdouble>,    // GetDoubleField
2639   _Jv_JNI_SetField,             // SetObjectField
2640   _Jv_JNI_SetField,             // SetBooleanField
2641   _Jv_JNI_SetField,             // SetByteField
2642   _Jv_JNI_SetField,             // SetCharField
2643   _Jv_JNI_SetField,             // SetShortField
2644   _Jv_JNI_SetField,             // SetIntField
2645   _Jv_JNI_SetField,             // SetLongField
2646   _Jv_JNI_SetField,             // SetFloatField
2647   _Jv_JNI_SetField,             // SetDoubleField
2648   _Jv_JNI_GetAnyMethodID<true>, // GetStaticMethodID
2649
2650   _Jv_JNI_CallStaticMethod<jobject>,      // CallStaticObjectMethod
2651   _Jv_JNI_CallStaticMethodV<jobject>,     // CallStaticObjectMethodV
2652   _Jv_JNI_CallStaticMethodA<jobject>,     // CallStaticObjectMethodA
2653   _Jv_JNI_CallStaticMethod<jboolean>,     // CallStaticBooleanMethod
2654   _Jv_JNI_CallStaticMethodV<jboolean>,    // CallStaticBooleanMethodV
2655   _Jv_JNI_CallStaticMethodA<jboolean>,    // CallStaticBooleanMethodA
2656   _Jv_JNI_CallStaticMethod<jbyte>,        // CallStaticByteMethod
2657   _Jv_JNI_CallStaticMethodV<jbyte>,       // CallStaticByteMethodV
2658   _Jv_JNI_CallStaticMethodA<jbyte>,       // CallStaticByteMethodA
2659   _Jv_JNI_CallStaticMethod<jchar>,        // CallStaticCharMethod
2660   _Jv_JNI_CallStaticMethodV<jchar>,       // CallStaticCharMethodV
2661   _Jv_JNI_CallStaticMethodA<jchar>,       // CallStaticCharMethodA
2662   _Jv_JNI_CallStaticMethod<jshort>,       // CallStaticShortMethod
2663   _Jv_JNI_CallStaticMethodV<jshort>,      // CallStaticShortMethodV
2664   _Jv_JNI_CallStaticMethodA<jshort>,      // CallStaticShortMethodA
2665   _Jv_JNI_CallStaticMethod<jint>,         // CallStaticIntMethod
2666   _Jv_JNI_CallStaticMethodV<jint>,        // CallStaticIntMethodV
2667   _Jv_JNI_CallStaticMethodA<jint>,        // CallStaticIntMethodA
2668   _Jv_JNI_CallStaticMethod<jlong>,        // CallStaticLongMethod
2669   _Jv_JNI_CallStaticMethodV<jlong>,       // CallStaticLongMethodV
2670   _Jv_JNI_CallStaticMethodA<jlong>,       // CallStaticLongMethodA
2671   _Jv_JNI_CallStaticMethod<jfloat>,       // CallStaticFloatMethod
2672   _Jv_JNI_CallStaticMethodV<jfloat>,      // CallStaticFloatMethodV
2673   _Jv_JNI_CallStaticMethodA<jfloat>,      // CallStaticFloatMethodA
2674   _Jv_JNI_CallStaticMethod<jdouble>,      // CallStaticDoubleMethod
2675   _Jv_JNI_CallStaticMethodV<jdouble>,     // CallStaticDoubleMethodV
2676   _Jv_JNI_CallStaticMethodA<jdouble>,     // CallStaticDoubleMethodA
2677   _Jv_JNI_CallStaticVoidMethod,           // CallStaticVoidMethod
2678   _Jv_JNI_CallStaticVoidMethodV,          // CallStaticVoidMethodV
2679   _Jv_JNI_CallStaticVoidMethodA,          // CallStaticVoidMethodA
2680
2681   _Jv_JNI_GetAnyFieldID<true>,         // GetStaticFieldID
2682   _Jv_JNI_GetStaticField<jobject>,     // GetStaticObjectField
2683   _Jv_JNI_GetStaticField<jboolean>,    // GetStaticBooleanField
2684   _Jv_JNI_GetStaticField<jbyte>,       // GetStaticByteField
2685   _Jv_JNI_GetStaticField<jchar>,       // GetStaticCharField
2686   _Jv_JNI_GetStaticField<jshort>,      // GetStaticShortField
2687   _Jv_JNI_GetStaticField<jint>,        // GetStaticIntField
2688   _Jv_JNI_GetStaticField<jlong>,       // GetStaticLongField
2689   _Jv_JNI_GetStaticField<jfloat>,      // GetStaticFloatField
2690   _Jv_JNI_GetStaticField<jdouble>,     // GetStaticDoubleField
2691   _Jv_JNI_SetStaticField,              // SetStaticObjectField
2692   _Jv_JNI_SetStaticField,              // SetStaticBooleanField
2693   _Jv_JNI_SetStaticField,              // SetStaticByteField
2694   _Jv_JNI_SetStaticField,              // SetStaticCharField
2695   _Jv_JNI_SetStaticField,              // SetStaticShortField
2696   _Jv_JNI_SetStaticField,              // SetStaticIntField
2697   _Jv_JNI_SetStaticField,              // SetStaticLongField
2698   _Jv_JNI_SetStaticField,              // SetStaticFloatField
2699   _Jv_JNI_SetStaticField,              // SetStaticDoubleField
2700   _Jv_JNI_NewString,                   // NewString
2701   _Jv_JNI_GetStringLength,             // GetStringLength
2702   _Jv_JNI_GetStringChars,              // GetStringChars
2703   _Jv_JNI_ReleaseStringChars,          // ReleaseStringChars
2704   _Jv_JNI_NewStringUTF,                // NewStringUTF
2705   _Jv_JNI_GetStringUTFLength,          // GetStringUTFLength
2706   _Jv_JNI_GetStringUTFChars,           // GetStringUTFChars
2707   _Jv_JNI_ReleaseStringUTFChars,       // ReleaseStringUTFChars
2708   _Jv_JNI_GetArrayLength,              // GetArrayLength
2709   _Jv_JNI_NewObjectArray,              // NewObjectArray
2710   _Jv_JNI_GetObjectArrayElement,       // GetObjectArrayElement
2711   _Jv_JNI_SetObjectArrayElement,       // SetObjectArrayElement
2712   _Jv_JNI_NewPrimitiveArray<jboolean, JvPrimClass (boolean)>,
2713                                                             // NewBooleanArray
2714   _Jv_JNI_NewPrimitiveArray<jbyte, JvPrimClass (byte)>,     // NewByteArray
2715   _Jv_JNI_NewPrimitiveArray<jchar, JvPrimClass (char)>,     // NewCharArray
2716   _Jv_JNI_NewPrimitiveArray<jshort, JvPrimClass (short)>,   // NewShortArray
2717   _Jv_JNI_NewPrimitiveArray<jint, JvPrimClass (int)>,       // NewIntArray
2718   _Jv_JNI_NewPrimitiveArray<jlong, JvPrimClass (long)>,     // NewLongArray
2719   _Jv_JNI_NewPrimitiveArray<jfloat, JvPrimClass (float)>,   // NewFloatArray
2720   _Jv_JNI_NewPrimitiveArray<jdouble, JvPrimClass (double)>, // NewDoubleArray
2721   _Jv_JNI_GetPrimitiveArrayElements<jboolean, JvPrimClass (boolean)>,       
2722                                             // GetBooleanArrayElements
2723   _Jv_JNI_GetPrimitiveArrayElements<jbyte, JvPrimClass (byte)>,  
2724                                             // GetByteArrayElements
2725   _Jv_JNI_GetPrimitiveArrayElements<jchar, JvPrimClass (char)>,
2726                                             // GetCharArrayElements
2727   _Jv_JNI_GetPrimitiveArrayElements<jshort, JvPrimClass (short)>,           
2728                                             // GetShortArrayElements
2729   _Jv_JNI_GetPrimitiveArrayElements<jint, JvPrimClass (int)>,               
2730                                             // GetIntArrayElements
2731   _Jv_JNI_GetPrimitiveArrayElements<jlong, JvPrimClass (long)>,             
2732                                             // GetLongArrayElements
2733   _Jv_JNI_GetPrimitiveArrayElements<jfloat, JvPrimClass (float)>,           
2734                                             // GetFloatArrayElements
2735   _Jv_JNI_GetPrimitiveArrayElements<jdouble, JvPrimClass (double)>,         
2736                                             // GetDoubleArrayElements
2737   _Jv_JNI_ReleasePrimitiveArrayElements<jboolean, JvPrimClass (boolean)>,    
2738                                             // ReleaseBooleanArrayElements
2739   _Jv_JNI_ReleasePrimitiveArrayElements<jbyte, JvPrimClass (byte)>,    
2740                                             // ReleaseByteArrayElements
2741   _Jv_JNI_ReleasePrimitiveArrayElements<jchar, JvPrimClass (char)>,    
2742                                             // ReleaseCharArrayElements
2743   _Jv_JNI_ReleasePrimitiveArrayElements<jshort, JvPrimClass (short)>,    
2744                                             // ReleaseShortArrayElements
2745   _Jv_JNI_ReleasePrimitiveArrayElements<jint, JvPrimClass (int)>,    
2746                                             // ReleaseIntArrayElements
2747   _Jv_JNI_ReleasePrimitiveArrayElements<jlong, JvPrimClass (long)>,    
2748                                             // ReleaseLongArrayElements
2749   _Jv_JNI_ReleasePrimitiveArrayElements<jfloat, JvPrimClass (float)>,    
2750                                             // ReleaseFloatArrayElements
2751   _Jv_JNI_ReleasePrimitiveArrayElements<jdouble, JvPrimClass (double)>,    
2752                                             // ReleaseDoubleArrayElements
2753   _Jv_JNI_GetPrimitiveArrayRegion<jboolean, JvPrimClass (boolean)>,         
2754                                             // GetBooleanArrayRegion
2755   _Jv_JNI_GetPrimitiveArrayRegion<jbyte, JvPrimClass (byte)>,       
2756                                             // GetByteArrayRegion
2757   _Jv_JNI_GetPrimitiveArrayRegion<jchar, JvPrimClass (char)>,       
2758                                             // GetCharArrayRegion
2759   _Jv_JNI_GetPrimitiveArrayRegion<jshort, JvPrimClass (short)>,     
2760                                             // GetShortArrayRegion
2761   _Jv_JNI_GetPrimitiveArrayRegion<jint, JvPrimClass (int)>,         
2762                                             // GetIntArrayRegion
2763   _Jv_JNI_GetPrimitiveArrayRegion<jlong, JvPrimClass (long)>,       
2764                                             // GetLongArrayRegion
2765   _Jv_JNI_GetPrimitiveArrayRegion<jfloat, JvPrimClass (float)>,     
2766                                             // GetFloatArrayRegion
2767   _Jv_JNI_GetPrimitiveArrayRegion<jdouble, JvPrimClass (double)>,           
2768                                             // GetDoubleArrayRegion
2769   _Jv_JNI_SetPrimitiveArrayRegion<jboolean, JvPrimClass (boolean)>,         
2770                                             // SetBooleanArrayRegion
2771   _Jv_JNI_SetPrimitiveArrayRegion<jbyte, JvPrimClass (byte)>,       
2772                                             // SetByteArrayRegion
2773   _Jv_JNI_SetPrimitiveArrayRegion<jchar, JvPrimClass (char)>,       
2774                                             // SetCharArrayRegion
2775   _Jv_JNI_SetPrimitiveArrayRegion<jshort, JvPrimClass (short)>,     
2776                                             // SetShortArrayRegion
2777   _Jv_JNI_SetPrimitiveArrayRegion<jint, JvPrimClass (int)>,         
2778                                             // SetIntArrayRegion
2779   _Jv_JNI_SetPrimitiveArrayRegion<jlong, JvPrimClass (long)>,       
2780                                             // SetLongArrayRegion
2781   _Jv_JNI_SetPrimitiveArrayRegion<jfloat, JvPrimClass (float)>,     
2782                                             // SetFloatArrayRegion
2783   _Jv_JNI_SetPrimitiveArrayRegion<jdouble, JvPrimClass (double)>,           
2784                                             // SetDoubleArrayRegion
2785   _Jv_JNI_RegisterNatives,                  // RegisterNatives
2786   _Jv_JNI_UnregisterNatives,                // UnregisterNatives
2787   _Jv_JNI_MonitorEnter,                     // MonitorEnter
2788   _Jv_JNI_MonitorExit,                      // MonitorExit
2789   _Jv_JNI_GetJavaVM,                        // GetJavaVM
2790
2791   _Jv_JNI_GetStringRegion,                  // GetStringRegion
2792   _Jv_JNI_GetStringUTFRegion,               // GetStringUTFRegion
2793   _Jv_JNI_GetPrimitiveArrayCritical,        // GetPrimitiveArrayCritical
2794   _Jv_JNI_ReleasePrimitiveArrayCritical,    // ReleasePrimitiveArrayCritical
2795   _Jv_JNI_GetStringCritical,                // GetStringCritical
2796   _Jv_JNI_ReleaseStringCritical,            // ReleaseStringCritical
2797
2798   _Jv_JNI_NewWeakGlobalRef,                 // NewWeakGlobalRef
2799   _Jv_JNI_DeleteWeakGlobalRef,              // DeleteWeakGlobalRef
2800
2801   _Jv_JNI_ExceptionCheck,                   // ExceptionCheck
2802
2803   _Jv_JNI_NewDirectByteBuffer,              // NewDirectByteBuffer
2804   _Jv_JNI_GetDirectBufferAddress,           // GetDirectBufferAddress
2805   _Jv_JNI_GetDirectBufferCapacity           // GetDirectBufferCapacity
2806 };
2807
2808 struct JNIInvokeInterface _Jv_JNI_InvokeFunctions =
2809 {
2810   RESERVED,
2811   RESERVED,
2812   RESERVED,
2813
2814   _Jv_JNI_DestroyJavaVM,
2815   _Jv_JNI_AttachCurrentThread,
2816   _Jv_JNI_DetachCurrentThread,
2817   _Jv_JNI_GetEnv,
2818   _Jv_JNI_AttachCurrentThreadAsDaemon
2819 };