OSDN Git Service

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