OSDN Git Service

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