OSDN Git Service

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