OSDN Git Service

* jni.cc (add_char): Added missing `else'.
[pf3gnuchains/gcc-fork.git] / libjava / jni.cc
1 // jni.cc - JNI implementation, including the jump table.
2
3 /* Copyright (C) 1998, 1999, 2000  Red Hat, Inc.
4
5    This file is part of libgcj.
6
7 This software is copyrighted work licensed under the terms of the
8 Libgcj License.  Please consult the file "LIBGCJ_LICENSE" for
9 details.  */
10
11 #include <config.h>
12
13 #include <stddef.h>
14 #include <string.h>
15
16 // Define this before including jni.h.
17 #define __GCJ_JNI_IMPL__
18
19 #include <gcj/cni.h>
20 #include <jvm.h>
21 #include <java-assert.h>
22 #include <jni.h>
23
24 #include <java/lang/Class.h>
25 #include <java/lang/ClassLoader.h>
26 #include <java/lang/Throwable.h>
27 #include <java/lang/ArrayIndexOutOfBoundsException.h>
28 #include <java/lang/StringIndexOutOfBoundsException.h>
29 #include <java/lang/AbstractMethodError.h>
30 #include <java/lang/InstantiationException.h>
31 #include <java/lang/NoSuchFieldError.h>
32 #include <java/lang/NoSuchMethodError.h>
33 #include <java/lang/reflect/Constructor.h>
34 #include <java/lang/reflect/Method.h>
35 #include <java/lang/reflect/Modifier.h>
36 #include <java/lang/OutOfMemoryError.h>
37 #include <java/util/Hashtable.h>
38 #include <java/lang/Integer.h>
39 #include <gnu/gcj/jni/NativeThread.h>
40
41 #include <gcj/method.h>
42 #include <gcj/field.h>
43
44 #include <java-interp.h>
45
46 #define ClassClass _CL_Q34java4lang5Class
47 extern java::lang::Class ClassClass;
48 #define ObjectClass _CL_Q34java4lang6Object
49 extern java::lang::Class ObjectClass;
50
51 #define ThrowableClass _CL_Q34java4lang9Throwable
52 extern java::lang::Class ThrowableClass;
53 #define MethodClass _CL_Q44java4lang7reflect6Method
54 extern java::lang::Class MethodClass;
55 #define ThreadGroupClass _CL_Q34java4lang11ThreadGroup
56 extern java::lang::Class ThreadGroupClass;
57 #define NativeThreadClass _CL_Q43gnu3gcj3jni12NativeThread
58 extern java::lang::Class ThreadGroupClass;
59
60 // This enum is used to select different template instantiations in
61 // the invocation code.
62 enum invocation_type
63 {
64   normal,
65   nonvirtual,
66   static_type,
67   constructor
68 };
69
70 // Forward declarations.
71 extern struct JNINativeInterface _Jv_JNIFunctions;
72 extern struct JNIInvokeInterface _Jv_JNI_InvokeFunctions;
73
74 // Number of slots in the default frame.  The VM must allow at least
75 // 16.
76 #define FRAME_SIZE 32
77
78 // This structure is used to keep track of local references.
79 struct _Jv_JNI_LocalFrame
80 {
81   // This is true if this frame object represents a pushed frame (eg
82   // from PushLocalFrame).
83   int marker :  1;
84
85   // Number of elements in frame.
86   int size   : 31;
87
88   // Next frame in chain.
89   _Jv_JNI_LocalFrame *next;
90
91   // The elements.  These are allocated using the C "struct hack".
92   jobject vec[0];
93 };
94
95 // This holds a reference count for all local and global references.
96 static java::util::Hashtable *ref_table;
97
98 // The only VM.
99 static JavaVM *the_vm;
100
101 \f
102
103 void
104 _Jv_JNI_Init (void)
105 {
106   ref_table = new java::util::Hashtable;
107 }
108
109 // Tell the GC that a certain pointer is live.
110 static void
111 mark_for_gc (jobject obj)
112 {
113   JvSynchronize sync (ref_table);
114
115   using namespace java::lang;
116   Integer *refcount = (Integer *) ref_table->get (obj);
117   jint val = (refcount == NULL) ? 0 : refcount->intValue ();
118   ref_table->put (obj, new Integer (val + 1));
119 }
120
121 // Unmark a pointer.
122 static void
123 unmark_for_gc (jobject obj)
124 {
125   JvSynchronize sync (ref_table);
126
127   using namespace java::lang;
128   Integer *refcount = (Integer *) ref_table->get (obj);
129   JvAssert (refcount);
130   jint val = refcount->intValue () - 1;
131   if (val == 0)
132     ref_table->remove (obj);
133   else
134     ref_table->put (obj, new Integer (val));
135 }
136
137 \f
138
139 static jobject
140 _Jv_JNI_NewGlobalRef (JNIEnv *, jobject obj)
141 {
142   mark_for_gc (obj);
143   return obj;
144 }
145
146 static void
147 _Jv_JNI_DeleteGlobalRef (JNIEnv *, jobject obj)
148 {
149   unmark_for_gc (obj);
150 }
151
152 static void
153 _Jv_JNI_DeleteLocalRef (JNIEnv *env, jobject obj)
154 {
155   _Jv_JNI_LocalFrame *frame;
156
157   for (frame = env->locals; frame != NULL; frame = frame->next)
158     {
159       for (int i = 0; i < FRAME_SIZE; ++i)
160         {
161           if (frame->vec[i] == obj)
162             {
163               frame->vec[i] = NULL;
164               unmark_for_gc (obj);
165               return;
166             }
167         }
168
169       // Don't go past a marked frame.
170       JvAssert (! frame->marker);
171     }
172
173   JvAssert (0);
174 }
175
176 static jint
177 _Jv_JNI_EnsureLocalCapacity (JNIEnv *env, jint size)
178 {
179   // It is easier to just always allocate a new frame of the requested
180   // size.  This isn't the most efficient thing, but for now we don't
181   // care.  Note that _Jv_JNI_PushLocalFrame relies on this right now.
182
183   _Jv_JNI_LocalFrame *frame
184     = (_Jv_JNI_LocalFrame *) _Jv_MallocUnchecked (sizeof (_Jv_JNI_LocalFrame)
185                                                   + size * sizeof (jobject));
186   if (frame == NULL)
187     {
188       // FIXME: exception processing.
189       env->ex = new java::lang::OutOfMemoryError;
190       return JNI_ERR;
191     }
192
193   frame->marker = true;
194   frame->size = size;
195   memset (&frame->vec[0], 0, size * sizeof (jobject));
196   frame->next = env->locals;
197   env->locals = frame;
198
199   return 0;
200 }
201
202 static jint
203 _Jv_JNI_PushLocalFrame (JNIEnv *env, jint size)
204 {
205   jint r = _Jv_JNI_EnsureLocalCapacity (env, size);
206   if (r < 0)
207     return r;
208
209   // The new frame is on top.
210   env->locals->marker = true;
211
212   return 0;
213 }
214
215 static jobject
216 _Jv_JNI_NewLocalRef (JNIEnv *env, jobject obj)
217 {
218   // Try to find an open slot somewhere in the topmost frame.
219   _Jv_JNI_LocalFrame *frame = env->locals;
220   bool done = false, set = false;
221   while (frame != NULL && ! done)
222     {
223       for (int i = 0; i < frame->size; ++i)
224         if (frame->vec[i] == NULL)
225           {
226             set = true;
227             done = true;
228             frame->vec[i] = obj;
229             break;
230           }
231     }
232
233   if (! set)
234     {
235       // No slots, so we allocate a new frame.  According to the spec
236       // we could just die here.  FIXME: return value.
237       _Jv_JNI_EnsureLocalCapacity (env, 16);
238       // We know the first element of the new frame will be ok.
239       env->locals->vec[0] = obj;
240     }
241
242   mark_for_gc (obj);
243   return obj;
244 }
245
246 static jobject
247 _Jv_JNI_PopLocalFrame (JNIEnv *env, jobject result)
248 {
249   _Jv_JNI_LocalFrame *rf = env->locals;
250
251   bool done = false;
252   while (rf != NULL && ! done)
253     {  
254       for (int i = 0; i < rf->size; ++i)
255         if (rf->vec[i] != NULL)
256           unmark_for_gc (rf->vec[i]);
257
258       // If the frame we just freed is the marker frame, we are done.
259       done = rf->marker;
260
261       _Jv_JNI_LocalFrame *n = rf->next;
262       // When N==NULL, we've reached the stack-allocated frame, and we
263       // must not free it.  However, we must be sure to clear all its
264       // elements, since we might conceivably reuse it.
265       if (n == NULL)
266         {
267           memset (&rf->vec[0], 0, rf->size * sizeof (jobject));
268           break;
269         }
270
271       _Jv_Free (rf);
272       rf = n;
273     }
274
275   return result == NULL ? NULL : _Jv_JNI_NewLocalRef (env, result);
276 }
277
278 // This function is used from other template functions.  It wraps the
279 // return value appropriately; we specialize it so that object returns
280 // are turned into local references.
281 template<typename T>
282 static T
283 wrap_value (JNIEnv *, T value)
284 {
285   return value;
286 }
287
288 template<>
289 static jobject
290 wrap_value (JNIEnv *env, jobject value)
291 {
292   return value == NULL ? value : _Jv_JNI_NewLocalRef (env, value);
293 }
294
295 \f
296
297 static jint
298 _Jv_JNI_GetVersion (JNIEnv *)
299 {
300   return JNI_VERSION_1_2;
301 }
302
303 static jclass
304 _Jv_JNI_DefineClass (JNIEnv *env, jobject loader, 
305                      const jbyte *buf, jsize bufLen)
306 {
307   jbyteArray bytes = JvNewByteArray (bufLen);
308   jbyte *elts = elements (bytes);
309   memcpy (elts, buf, bufLen * sizeof (jbyte));
310
311   java::lang::ClassLoader *l
312     = reinterpret_cast<java::lang::ClassLoader *> (loader);
313
314   // FIXME: exception processing.
315   jclass result = l->defineClass (bytes, 0, bufLen);
316   return (jclass) wrap_value (env, result);
317 }
318
319 static jclass
320 _Jv_JNI_FindClass (JNIEnv *env, const char *name)
321 {
322   // FIXME: assume that NAME isn't too long.
323   int len = strlen (name);
324   char s[len + 1];
325   for (int i = 0; i <= len; ++i)
326     s[i] = (name[i] == '/') ? '.' : name[i];
327   jstring n = JvNewStringUTF (s);
328
329   java::lang::ClassLoader *loader;
330   if (env->klass == NULL)
331     {
332       // FIXME: should use getBaseClassLoader, but we don't have that
333       // yet.
334       loader = java::lang::ClassLoader::getSystemClassLoader ();
335     }
336   else
337     loader = env->klass->getClassLoader ();
338
339   // FIXME: exception processing.
340   jclass r = loader->findClass (n);
341
342   return (jclass) wrap_value (env, r);
343 }
344
345 static jclass
346 _Jv_JNI_GetSuperclass (JNIEnv *env, jclass clazz)
347 {
348   return (jclass) wrap_value (env, clazz->getSuperclass ());
349 }
350
351 static jboolean
352 _Jv_JNI_IsAssignableFrom(JNIEnv *, jclass clazz1, jclass clazz2)
353 {
354   return clazz1->isAssignableFrom (clazz2);
355 }
356
357 static jint
358 _Jv_JNI_Throw (JNIEnv *env, jthrowable obj)
359 {
360   // We check in case the user did some funky cast.
361   JvAssert (obj != NULL && (&ThrowableClass)->isInstance (obj));
362   env->ex = obj;
363   return 0;
364 }
365
366 static jint
367 _Jv_JNI_ThrowNew (JNIEnv *env, jclass clazz, const char *message)
368 {
369   using namespace java::lang::reflect;
370
371   JvAssert ((&ThrowableClass)->isAssignableFrom (clazz));
372
373   JArray<jclass> *argtypes
374     = (JArray<jclass> *) JvNewObjectArray (1, &ClassClass, NULL);
375
376   jclass *elts = elements (argtypes);
377   elts[0] = &StringClass;
378
379   // FIXME: exception processing.
380   Constructor *cons = clazz->getConstructor (argtypes);
381
382   jobjectArray values = JvNewObjectArray (1, &StringClass, NULL);
383   jobject *velts = elements (values);
384   velts[0] = JvNewStringUTF (message);
385
386   // FIXME: exception processing.
387   jobject obj = cons->newInstance (values);
388
389   env->ex = reinterpret_cast<jthrowable> (obj);
390   return 0;
391 }
392
393 static jthrowable
394 _Jv_JNI_ExceptionOccurred (JNIEnv *env)
395 {
396   return (jthrowable) wrap_value (env, env->ex);
397 }
398
399 static void
400 _Jv_JNI_ExceptionDescribe (JNIEnv *env)
401 {
402   if (env->ex != NULL)
403     env->ex->printStackTrace();
404 }
405
406 static void
407 _Jv_JNI_ExceptionClear (JNIEnv *env)
408 {
409   env->ex = NULL;
410 }
411
412 static jboolean
413 _Jv_JNI_ExceptionCheck (JNIEnv *env)
414 {
415   return env->ex != NULL;
416 }
417
418 static void
419 _Jv_JNI_FatalError (JNIEnv *, const char *message)
420 {
421   JvFail (message);
422 }
423
424 \f
425
426 static jboolean
427 _Jv_JNI_IsSameObject (JNIEnv *, jobject obj1, jobject obj2)
428 {
429   return obj1 == obj2;
430 }
431
432 static jobject
433 _Jv_JNI_AllocObject (JNIEnv *env, jclass clazz)
434 {
435   jobject obj = NULL;
436   using namespace java::lang::reflect;
437
438   JvAssert (clazz && ! clazz->isArray ());
439   if (clazz->isInterface() || Modifier::isAbstract(clazz->getModifiers()))
440     env->ex = new java::lang::InstantiationException ();
441   else
442     {
443       // FIXME: exception processing.
444       // FIXME: will this work for String?
445       obj = JvAllocObject (clazz);
446     }
447
448   return wrap_value (env, obj);
449 }
450
451 static jclass
452 _Jv_JNI_GetObjectClass (JNIEnv *env, jobject obj)
453 {
454   JvAssert (obj);
455   return (jclass) wrap_value (env, obj->getClass());
456 }
457
458 static jboolean
459 _Jv_JNI_IsInstanceOf (JNIEnv *, jobject obj, jclass clazz)
460 {
461   return clazz->isInstance(obj);
462 }
463
464 \f
465
466 //
467 // This section concerns method invocation.
468 //
469
470 template<jboolean is_static>
471 static jmethodID
472 _Jv_JNI_GetAnyMethodID (JNIEnv *env, jclass clazz,
473                         const char *name, const char *sig)
474 {
475   // FIXME: exception processing.
476   _Jv_InitClass (clazz);
477
478   _Jv_Utf8Const *name_u = _Jv_makeUtf8Const ((char *) name, -1);
479   _Jv_Utf8Const *sig_u = _Jv_makeUtf8Const ((char *) sig, -1);
480
481   JvAssert (! clazz->isPrimitive());
482
483   using namespace java::lang::reflect;
484
485   while (clazz != NULL)
486     {
487       jint count = JvNumMethods (clazz);
488       jmethodID meth = JvGetFirstMethod (clazz);
489
490       for (jint i = 0; i < count; ++i)
491         {
492           if (((is_static && Modifier::isStatic (meth->accflags))
493                || (! is_static && ! Modifier::isStatic (meth->accflags)))
494               && _Jv_equalUtf8Consts (meth->name, name_u)
495               && _Jv_equalUtf8Consts (meth->signature, sig_u))
496             return meth;
497
498           meth = meth->getNextMethod();
499         }
500
501       clazz = clazz->getSuperclass ();
502     }
503
504   env->ex = new java::lang::NoSuchMethodError ();
505   return NULL;
506 }
507
508 // This is a helper function which turns a va_list into an array of
509 // `jvalue's.  It needs signature information in order to do its work.
510 // The array of values must already be allocated.
511 static void
512 array_from_valist (jvalue *values, JArray<jclass> *arg_types, va_list vargs)
513 {
514   jclass *arg_elts = elements (arg_types);
515   for (int i = 0; i < arg_types->length; ++i)
516     {
517       if (arg_elts[i] == JvPrimClass (byte))
518         values[i].b = va_arg (vargs, jbyte);
519       else if (arg_elts[i] == JvPrimClass (short))
520         values[i].s = va_arg (vargs, jshort);
521       else if (arg_elts[i] == JvPrimClass (int))
522         values[i].i = va_arg (vargs, jint);
523       else if (arg_elts[i] == JvPrimClass (long))
524         values[i].j = va_arg (vargs, jlong);
525       else if (arg_elts[i] == JvPrimClass (float))
526         values[i].f = va_arg (vargs, jfloat);
527       else if (arg_elts[i] == JvPrimClass (double))
528         values[i].d = va_arg (vargs, jdouble);
529       else if (arg_elts[i] == JvPrimClass (boolean))
530         values[i].z = va_arg (vargs, jboolean);
531       else if (arg_elts[i] == JvPrimClass (char))
532         values[i].c = va_arg (vargs, jchar);
533       else
534         {
535           // An object.
536           values[i].l = va_arg (vargs, jobject);
537         }
538     }
539 }
540
541 // This can call any sort of method: virtual, "nonvirtual", static, or
542 // constructor.
543 template<typename T, invocation_type style>
544 static T
545 _Jv_JNI_CallAnyMethodV (JNIEnv *env, jobject obj, jclass klass,
546                         jmethodID id, va_list vargs)
547 {
548   if (style == normal)
549     id = _Jv_LookupDeclaredMethod (obj->getClass (), id->name, id->signature);
550
551   jclass decl_class = klass ? klass : obj->getClass ();
552   JvAssert (decl_class != NULL);
553
554   jclass return_type;
555   JArray<jclass> *arg_types;
556   // FIXME: exception processing.
557   _Jv_GetTypesFromSignature (id, decl_class,
558                              &arg_types, &return_type);
559
560   jvalue args[arg_types->length];
561   array_from_valist (args, arg_types, vargs);
562
563   jvalue result;
564   jthrowable ex = _Jv_CallAnyMethodA (obj, return_type, id,
565                                       style == constructor,
566                                       arg_types, args, &result);
567
568   if (ex != NULL)
569     env->ex = ex;
570
571   // We cheat a little here.  FIXME.
572   return wrap_value (env, * (T *) &result);
573 }
574
575 template<typename T, invocation_type style>
576 static T
577 _Jv_JNI_CallAnyMethod (JNIEnv *env, jobject obj, jclass klass,
578                        jmethodID method, ...)
579 {
580   va_list args;
581   T result;
582
583   va_start (args, method);
584   result = _Jv_JNI_CallAnyMethodV<T, style> (env, obj, klass, method, args);
585   va_end (args);
586
587   return result;
588 }
589
590 template<typename T, invocation_type style>
591 static T
592 _Jv_JNI_CallAnyMethodA (JNIEnv *env, jobject obj, jclass klass,
593                         jmethodID id, jvalue *args)
594 {
595   if (style == normal)
596     id = _Jv_LookupDeclaredMethod (obj->getClass (), id->name, id->signature);
597
598   jclass decl_class = klass ? klass : obj->getClass ();
599   JvAssert (decl_class != NULL);
600
601   jclass return_type;
602   JArray<jclass> *arg_types;
603   // FIXME: exception processing.
604   _Jv_GetTypesFromSignature (id, decl_class,
605                              &arg_types, &return_type);
606
607   jvalue result;
608   jthrowable ex = _Jv_CallAnyMethodA (obj, return_type, id,
609                                       style == constructor,
610                                       arg_types, args, &result);
611
612   if (ex != NULL)
613     env->ex = ex;
614
615   // We cheat a little here.  FIXME.
616   return wrap_value (env, * (T *) &result);
617 }
618
619 template<invocation_type style>
620 static void
621 _Jv_JNI_CallAnyVoidMethodV (JNIEnv *env, jobject obj, jclass klass,
622                             jmethodID id, va_list vargs)
623 {
624   if (style == normal)
625     id = _Jv_LookupDeclaredMethod (obj->getClass (), id->name, id->signature);
626
627   jclass decl_class = klass ? klass : obj->getClass ();
628   JvAssert (decl_class != NULL);
629
630   jclass return_type;
631   JArray<jclass> *arg_types;
632   // FIXME: exception processing.
633   _Jv_GetTypesFromSignature (id, decl_class,
634                              &arg_types, &return_type);
635
636   jvalue args[arg_types->length];
637   array_from_valist (args, arg_types, vargs);
638
639   jthrowable ex = _Jv_CallAnyMethodA (obj, return_type, id,
640                                       style == constructor,
641                                       arg_types, args, NULL);
642
643   if (ex != NULL)
644     env->ex = ex;
645 }
646
647 template<invocation_type style>
648 static void
649 _Jv_JNI_CallAnyVoidMethod (JNIEnv *env, jobject obj, jclass klass,
650                            jmethodID method, ...)
651 {
652   va_list args;
653
654   va_start (args, method);
655   _Jv_JNI_CallAnyVoidMethodV<style> (env, obj, klass, method, args);
656   va_end (args);
657 }
658
659 template<invocation_type style>
660 static void
661 _Jv_JNI_CallAnyVoidMethodA (JNIEnv *env, jobject obj, jclass klass,
662                             jmethodID id, jvalue *args)
663 {
664   if (style == normal)
665     id = _Jv_LookupDeclaredMethod (obj->getClass (), id->name, id->signature);
666
667   jclass decl_class = klass ? klass : obj->getClass ();
668   JvAssert (decl_class != NULL);
669
670   jclass return_type;
671   JArray<jclass> *arg_types;
672   // FIXME: exception processing.
673   _Jv_GetTypesFromSignature (id, decl_class,
674                              &arg_types, &return_type);
675
676   jthrowable ex = _Jv_CallAnyMethodA (obj, return_type, id,
677                                       style == constructor,
678                                       arg_types, args, NULL);
679
680   if (ex != NULL)
681     env->ex = ex;
682 }
683
684 // Functions with this signature are used to implement functions in
685 // the CallMethod family.
686 template<typename T>
687 static T
688 _Jv_JNI_CallMethodV (JNIEnv *env, jobject obj, jmethodID id, va_list args)
689 {
690   return _Jv_JNI_CallAnyMethodV<T, normal> (env, obj, NULL, id, args);
691 }
692
693 // Functions with this signature are used to implement functions in
694 // the CallMethod family.
695 template<typename T>
696 static T
697 _Jv_JNI_CallMethod (JNIEnv *env, jobject obj, jmethodID id, ...)
698 {
699   va_list args;
700   T result;
701
702   va_start (args, id);
703   result = _Jv_JNI_CallAnyMethodV<T, normal> (env, obj, NULL, id, args);
704   va_end (args);
705
706   return result;
707 }
708
709 // Functions with this signature are used to implement functions in
710 // the CallMethod family.
711 template<typename T>
712 static T
713 _Jv_JNI_CallMethodA (JNIEnv *env, jobject obj, jmethodID id, jvalue *args)
714 {
715   return _Jv_JNI_CallAnyMethodA<T, normal> (env, obj, NULL, id, args);
716 }
717
718 static void
719 _Jv_JNI_CallVoidMethodV (JNIEnv *env, jobject obj, jmethodID id, va_list args)
720 {
721   _Jv_JNI_CallAnyVoidMethodV<normal> (env, obj, NULL, id, args);
722 }
723
724 static void
725 _Jv_JNI_CallVoidMethod (JNIEnv *env, jobject obj, jmethodID id, ...)
726 {
727   va_list args;
728
729   va_start (args, id);
730   _Jv_JNI_CallAnyVoidMethodV<normal> (env, obj, NULL, id, args);
731   va_end (args);
732 }
733
734 static void
735 _Jv_JNI_CallVoidMethodA (JNIEnv *env, jobject obj, jmethodID id, jvalue *args)
736 {
737   _Jv_JNI_CallAnyVoidMethodA<normal> (env, obj, NULL, id, args);
738 }
739
740 // Functions with this signature are used to implement functions in
741 // the CallStaticMethod family.
742 template<typename T>
743 static T
744 _Jv_JNI_CallStaticMethodV (JNIEnv *env, jclass klass,
745                            jmethodID id, va_list args)
746 {
747   return _Jv_JNI_CallAnyMethodV<T, static_type> (env, NULL, klass, id, args);
748 }
749
750 // Functions with this signature are used to implement functions in
751 // the CallStaticMethod family.
752 template<typename T>
753 static T
754 _Jv_JNI_CallStaticMethod (JNIEnv *env, jclass klass, jmethodID id, ...)
755 {
756   va_list args;
757   T result;
758
759   va_start (args, id);
760   result = _Jv_JNI_CallAnyMethodV<T, static_type> (env, NULL, klass,
761                                                    id, args);
762   va_end (args);
763
764   return result;
765 }
766
767 // Functions with this signature are used to implement functions in
768 // the CallStaticMethod family.
769 template<typename T>
770 static T
771 _Jv_JNI_CallStaticMethodA (JNIEnv *env, jclass klass, jmethodID id,
772                            jvalue *args)
773 {
774   return _Jv_JNI_CallAnyMethodA<T, static_type> (env, NULL, klass, id, args);
775 }
776
777 static void
778 _Jv_JNI_CallStaticVoidMethodV (JNIEnv *env, jclass klass, jmethodID id,
779                                va_list args)
780 {
781   _Jv_JNI_CallAnyVoidMethodV<static_type> (env, NULL, klass, id, args);
782 }
783
784 static void
785 _Jv_JNI_CallStaticVoidMethod (JNIEnv *env, jclass klass, jmethodID id, ...)
786 {
787   va_list args;
788
789   va_start (args, id);
790   _Jv_JNI_CallAnyVoidMethodV<static_type> (env, NULL, klass, id, args);
791   va_end (args);
792 }
793
794 static void
795 _Jv_JNI_CallStaticVoidMethodA (JNIEnv *env, jclass klass, jmethodID id,
796                                jvalue *args)
797 {
798   _Jv_JNI_CallAnyVoidMethodA<static_type> (env, NULL, klass, id, args);
799 }
800
801 static jobject
802 _Jv_JNI_NewObjectV (JNIEnv *env, jclass klass,
803                     jmethodID id, va_list args)
804 {
805   JvAssert (klass && ! klass->isArray ());
806   JvAssert (! strcmp (id->name->data, "<init>")
807             && ! strcmp (id->signature->data, "()V"));
808   return _Jv_JNI_CallAnyMethodV<jobject, constructor> (env, NULL, klass,
809                                                        id, args);
810 }
811
812 static jobject
813 _Jv_JNI_NewObject (JNIEnv *env, jclass klass, jmethodID id, ...)
814 {
815   JvAssert (klass && ! klass->isArray ());
816   JvAssert (! strcmp (id->name->data, "<init>")
817             && ! strcmp (id->signature->data, "()V"));
818
819   va_list args;
820   jobject result;
821
822   va_start (args, id);
823   result = _Jv_JNI_CallAnyMethodV<jobject, constructor> (env, NULL, klass,
824                                                          id, args);
825   va_end (args);
826
827   return result;
828 }
829
830 static jobject
831 _Jv_JNI_NewObjectA (JNIEnv *env, jclass klass, jmethodID id,
832                     jvalue *args)
833 {
834   JvAssert (klass && ! klass->isArray ());
835   JvAssert (! strcmp (id->name->data, "<init>")
836             && ! strcmp (id->signature->data, "()V"));
837   return _Jv_JNI_CallAnyMethodA<jobject, constructor> (env, NULL, klass,
838                                                        id, args);
839 }
840
841 \f
842
843 template<typename T>
844 static T
845 _Jv_JNI_GetField (JNIEnv *env, jobject obj, jfieldID field) 
846 {
847   JvAssert (obj);
848   T *ptr = (T *) ((char *) obj + field->getOffset ());
849   return wrap_value (env, *ptr);
850 }
851
852 template<typename T>
853 static void
854 _Jv_JNI_SetField (JNIEnv *, jobject obj, jfieldID field, T value)
855 {
856   JvAssert (obj);
857   T *ptr = (T *) ((char *) obj + field->getOffset ());
858   *ptr = value;
859 }
860
861 template<jboolean is_static>
862 static jfieldID
863 _Jv_JNI_GetAnyFieldID (JNIEnv *env, jclass clazz,
864                        const char *name, const char *sig)
865 {
866   // FIXME: exception processing.
867   _Jv_InitClass (clazz);
868
869   _Jv_Utf8Const *a_name = _Jv_makeUtf8Const ((char *) name, -1);
870
871   jclass field_class = NULL;
872   if (sig[0] == '[')
873     field_class = _Jv_FindClassFromSignature ((char *) sig, NULL);
874   else
875     {
876       _Jv_Utf8Const *sig_u = _Jv_makeUtf8Const ((char *) sig, -1);
877       field_class = _Jv_FindClass (sig_u, NULL);
878     }
879
880   // FIXME: what if field_class == NULL?
881
882   while (clazz != NULL)
883     {
884       jint count = (is_static
885                     ? JvNumStaticFields (clazz)
886                     : JvNumInstanceFields (clazz));
887       jfieldID field = (is_static
888                         ? JvGetFirstStaticField (clazz)
889                         : JvGetFirstInstanceField (clazz));
890       for (jint i = 0; i < count; ++i)
891         {
892           // The field is resolved as a side effect of class
893           // initialization.
894           JvAssert (field->isResolved ());
895
896           _Jv_Utf8Const *f_name = field->getNameUtf8Const(clazz);
897
898           if (_Jv_equalUtf8Consts (f_name, a_name)
899               && field->getClass() == field_class)
900             return field;
901
902           field = field->getNextField ();
903         }
904
905       clazz = clazz->getSuperclass ();
906     }
907
908   env->ex = new java::lang::NoSuchFieldError ();
909   return NULL;
910 }
911
912 template<typename T>
913 static T
914 _Jv_JNI_GetStaticField (JNIEnv *env, jclass, jfieldID field)
915 {
916   T *ptr = (T *) field->u.addr;
917   return wrap_value (env, *ptr);
918 }
919
920 template<typename T>
921 static void
922 _Jv_JNI_SetStaticField (JNIEnv *, jclass, jfieldID field, T value)
923 {
924   T *ptr = (T *) field->u.addr;
925   *ptr = value;
926 }
927
928 static jstring
929 _Jv_JNI_NewString (JNIEnv *env, const jchar *unichars, jsize len)
930 {
931   // FIXME: exception processing.
932   jstring r = _Jv_NewString (unichars, len);
933   return (jstring) wrap_value (env, r);
934 }
935
936 static jsize
937 _Jv_JNI_GetStringLength (JNIEnv *, jstring string)
938 {
939   return string->length();
940 }
941
942 static const jchar *
943 _Jv_JNI_GetStringChars (JNIEnv *, jstring string, jboolean *isCopy)
944 {
945   jchar *result = _Jv_GetStringChars (string);
946   mark_for_gc (string);
947   if (isCopy)
948     *isCopy = false;
949   return (const jchar *) result;
950 }
951
952 static void
953 _Jv_JNI_ReleaseStringChars (JNIEnv *, jstring string, const jchar *)
954 {
955   unmark_for_gc (string);
956 }
957
958 static jstring
959 _Jv_JNI_NewStringUTF (JNIEnv *env, const char *bytes)
960 {
961   // FIXME: exception processing.
962   jstring result = JvNewStringUTF (bytes);
963   return (jstring) wrap_value (env, result);
964 }
965
966 static jsize
967 _Jv_JNI_GetStringUTFLength (JNIEnv *, jstring string)
968 {
969   return JvGetStringUTFLength (string);
970 }
971
972 static const char *
973 _Jv_JNI_GetStringUTFChars (JNIEnv *, jstring string, jboolean *isCopy)
974 {
975   jsize len = JvGetStringUTFLength (string);
976   // FIXME: exception processing.
977   char *r = (char *) _Jv_Malloc (len + 1);
978   JvGetStringUTFRegion (string, 0, len, r);
979   r[len] = '\0';
980
981   if (isCopy)
982     *isCopy = true;
983
984   return (const char *) r;
985 }
986
987 static void
988 _Jv_JNI_ReleaseStringUTFChars (JNIEnv *, jstring, const char *utf)
989 {
990   _Jv_Free ((void *) utf);
991 }
992
993 static void
994 _Jv_JNI_GetStringRegion (JNIEnv *env, jstring string, jsize start, jsize len,
995                          jchar *buf)
996 {
997   jchar *result = _Jv_GetStringChars (string);
998   if (start < 0 || start > string->length ()
999       || len < 0 || start + len > string->length ())
1000     env->ex = new java::lang::StringIndexOutOfBoundsException ();
1001   else
1002     memcpy (buf, &result[start], len * sizeof (jchar));
1003 }
1004
1005 static void
1006 _Jv_JNI_GetStringUTFRegion (JNIEnv *env, jstring str, jsize start,
1007                             jsize len, char *buf)
1008 {
1009   if (start < 0 || start > str->length ()
1010       || len < 0 || start + len > str->length ())
1011     env->ex = new java::lang::StringIndexOutOfBoundsException ();
1012   else
1013     _Jv_GetStringUTFRegion (str, start, len, buf);
1014 }
1015
1016 static const jchar *
1017 _Jv_JNI_GetStringCritical (JNIEnv *, jstring str, jboolean *isCopy)
1018 {
1019   jchar *result = _Jv_GetStringChars (str);
1020   if (isCopy)
1021     *isCopy = false;
1022   return result;
1023 }
1024
1025 static void
1026 _Jv_JNI_ReleaseStringCritical (JNIEnv *, jstring, const jchar *)
1027 {
1028   // Nothing.
1029 }
1030
1031 static jsize
1032 _Jv_JNI_GetArrayLength (JNIEnv *, jarray array)
1033 {
1034   return array->length;
1035 }
1036
1037 static jarray
1038 _Jv_JNI_NewObjectArray (JNIEnv *env, jsize length, jclass elementClass,
1039                         jobject init)
1040 {
1041   // FIXME: exception processing.
1042   jarray result = JvNewObjectArray (length, elementClass, init);
1043   return (jarray) wrap_value (env, result);
1044 }
1045
1046 static jobject
1047 _Jv_JNI_GetObjectArrayElement (JNIEnv *env, jobjectArray array, jsize index)
1048 {
1049   jobject *elts = elements (array);
1050   return wrap_value (env, elts[index]);
1051 }
1052
1053 static void
1054 _Jv_JNI_SetObjectArrayElement (JNIEnv *, jobjectArray array, jsize index,
1055                                jobject value)
1056 {
1057   // FIXME: exception processing.
1058   _Jv_CheckArrayStore (array, value);
1059   jobject *elts = elements (array);
1060   elts[index] = value;
1061 }
1062
1063 template<typename T, jclass K>
1064 static JArray<T> *
1065 _Jv_JNI_NewPrimitiveArray (JNIEnv *env, jsize length)
1066 {
1067   // FIXME: exception processing.
1068   return (JArray<T> *) wrap_value (env, _Jv_NewPrimArray (K, length));
1069 }
1070
1071 template<typename T>
1072 static T *
1073 _Jv_JNI_GetPrimitiveArrayElements (JNIEnv *, JArray<T> *array,
1074                                    jboolean *isCopy)
1075 {
1076   T *elts = elements (array);
1077   if (isCopy)
1078     {
1079       // We elect never to copy.
1080       *isCopy = false;
1081     }
1082   mark_for_gc (array);
1083   return elts;
1084 }
1085
1086 template<typename T>
1087 static void
1088 _Jv_JNI_ReleasePrimitiveArrayElements (JNIEnv *, JArray<T> *array,
1089                                        T *, jint /* mode */)
1090 {
1091   // Note that we ignore MODE.  We can do this because we never copy
1092   // the array elements.  My reading of the JNI documentation is that
1093   // this is an option for the implementor.
1094   unmark_for_gc (array);
1095 }
1096
1097 template<typename T>
1098 static void
1099 _Jv_JNI_GetPrimitiveArrayRegion (JNIEnv *env, JArray<T> *array,
1100                                  jsize start, jsize len,
1101                                  T *buf)
1102 {
1103   if (start < 0 || len >= array->length || start + len >= array->length)
1104     {
1105       // FIXME: index.
1106       env->ex = new java::lang::ArrayIndexOutOfBoundsException ();
1107     }
1108   else
1109     {
1110       T *elts = elements (array) + start;
1111       memcpy (buf, elts, len * sizeof (T));
1112     }
1113 }
1114
1115 template<typename T>
1116 static void
1117 _Jv_JNI_SetPrimitiveArrayRegion (JNIEnv *env, JArray<T> *array, 
1118                                  jsize start, jsize len, T *buf)
1119 {
1120   if (start < 0 || len >= array->length || start + len >= array->length)
1121     {
1122       // FIXME: index.
1123       env->ex = new java::lang::ArrayIndexOutOfBoundsException ();
1124     }
1125   else
1126     {
1127       T *elts = elements (array) + start;
1128       memcpy (elts, buf, len * sizeof (T));
1129     }
1130 }
1131
1132 static void *
1133 _Jv_JNI_GetPrimitiveArrayCritical (JNIEnv *, jarray array,
1134                                    jboolean *isCopy)
1135 {
1136   // FIXME: does this work?
1137   jclass klass = array->getClass()->getComponentType();
1138   JvAssert (klass->isPrimitive ());
1139   char *r = _Jv_GetArrayElementFromElementType (array, klass);
1140   if (isCopy)
1141     *isCopy = false;
1142   return r;
1143 }
1144
1145 static void
1146 _Jv_JNI_ReleasePrimitiveArrayCritical (JNIEnv *, jarray, void *, jint)
1147 {
1148   // Nothing.
1149 }
1150
1151 static jint
1152 _Jv_JNI_MonitorEnter (JNIEnv *, jobject obj)
1153 {
1154   // FIXME: exception processing.
1155   jint r = _Jv_MonitorEnter (obj);
1156   return r;
1157 }
1158
1159 static jint
1160 _Jv_JNI_MonitorExit (JNIEnv *, jobject obj)
1161 {
1162   // FIXME: exception processing.
1163   jint r = _Jv_MonitorExit (obj);
1164   return r;
1165 }
1166
1167 // JDK 1.2
1168 jobject
1169 _Jv_JNI_ToReflectedField (JNIEnv *env, jclass cls, jfieldID fieldID,
1170                           jboolean)
1171 {
1172   // FIXME: exception processing.
1173   java::lang::reflect::Field *field = new java::lang::reflect::Field();
1174   field->declaringClass = cls;
1175   field->offset = (char*) fieldID - (char *) cls->fields;
1176   field->name = _Jv_NewStringUtf8Const (fieldID->getNameUtf8Const (cls));
1177   return wrap_value (env, field);
1178 }
1179
1180 // JDK 1.2
1181 static jfieldID
1182 _Jv_JNI_FromReflectedField (JNIEnv *, jobject f)
1183 {
1184   using namespace java::lang::reflect;
1185
1186   Field *field = reinterpret_cast<Field *> (f);
1187   return _Jv_FromReflectedField (field);
1188 }
1189
1190 jobject
1191 _Jv_JNI_ToReflectedMethod (JNIEnv *env, jclass klass, jmethodID id,
1192                            jboolean)
1193 {
1194   using namespace java::lang::reflect;
1195
1196   // FIXME.
1197   static _Jv_Utf8Const *init_name = _Jv_makeUtf8Const ("<init>", 6);
1198
1199   jobject result;
1200   if (_Jv_equalUtf8Consts (id->name, init_name))
1201     {
1202       // A constructor.
1203       Constructor *cons = new Constructor ();
1204       cons->offset = (char *) id - (char *) &klass->methods;
1205       cons->declaringClass = klass;
1206       result = cons;
1207     }
1208   else
1209     {
1210       Method *meth = new Method ();
1211       meth->offset = (char *) id - (char *) &klass->methods;
1212       meth->declaringClass = klass;
1213       result = meth;
1214     }
1215
1216   return wrap_value (env, result);
1217 }
1218
1219 static jmethodID
1220 _Jv_JNI_FromReflectedMethod (JNIEnv *, jobject method)
1221 {
1222   using namespace java::lang::reflect;
1223   if ((&MethodClass)->isInstance (method))
1224     return _Jv_FromReflectedMethod (reinterpret_cast<Method *> (method));
1225   return
1226     _Jv_FromReflectedConstructor (reinterpret_cast<Constructor *> (method));
1227 }
1228
1229 \f
1230
1231 #ifdef INTERPRETER
1232
1233 // Add a character to the buffer, encoding properly.
1234 static void
1235 add_char (char *buf, jchar c, int *here)
1236 {
1237   if (c == '_')
1238     {
1239       buf[(*here)++] = '_';
1240       buf[(*here)++] = '1';
1241     }
1242   else if (c == ';')
1243     {
1244       buf[(*here)++] = '_';
1245       buf[(*here)++] = '2';
1246     }
1247   else if (c == '[')
1248     {
1249       buf[(*here)++] = '_';
1250       buf[(*here)++] = '3';
1251     }
1252   else if (c == '/')
1253     buf[(*here)++] = '_';
1254   else if ((c >= '0' && c <= '9')
1255       || (c >= 'a' && c <= 'z')
1256       || (c >= 'A' && c <= 'Z'))
1257     buf[(*here)++] = (char) c;
1258   else
1259     {
1260       // "Unicode" character.
1261       buf[(*here)++] = '_';
1262       buf[(*here)++] = '0';
1263       for (int i = 0; i < 4; ++i)
1264         {
1265           int val = c & 0x0f;
1266           buf[(*here) + 4 - i] = (val > 10) ? ('a' + val - 10) : ('0' + val);
1267           c >>= 4;
1268         }
1269       *here += 4;
1270     }
1271 }
1272
1273 // Compute a mangled name for a native function.  This computes the
1274 // long name, and also returns an index which indicates where a NUL
1275 // can be placed to create the short name.  This function assumes that
1276 // the buffer is large enough for its results.
1277 static void
1278 mangled_name (jclass klass, _Jv_Utf8Const *func_name,
1279               _Jv_Utf8Const *signature, char *buf, int *long_start)
1280 {
1281   strcpy (buf, "Java_");
1282   int here = 5;
1283
1284   // Add fully qualified class name.
1285   jchar *chars = _Jv_GetStringChars (klass->getName ());
1286   jint len = klass->getName ()->length ();
1287   for (int i = 0; i < len; ++i)
1288     add_char (buf, chars[i], &here);
1289
1290   // Don't use add_char because we need a literal `_'.
1291   buf[here++] = '_';
1292
1293   const unsigned char *fn = (const unsigned char *) func_name->data;
1294   const unsigned char *limit = fn + func_name->length;
1295   for (int i = 0; ; ++i)
1296     {
1297       int ch = UTF8_GET (fn, limit);
1298       if (ch < 0)
1299         break;
1300       add_char (buf, ch, &here);
1301     }
1302
1303   // This is where the long signature begins.
1304   *long_start = here;
1305   buf[here++] = '_';
1306   buf[here++] = '_';
1307
1308   const unsigned char *sig = (const unsigned char *) signature->data;
1309   limit = sig + signature->length;
1310   JvAssert (signature[0] == '(');
1311   for (int i = 1; ; ++i)
1312     {
1313       int ch = UTF8_GET (sig, limit);
1314       if (ch == ')' || ch < 0)
1315         break;
1316       add_char (buf, ch, &here);
1317     }
1318
1319   buf[here] = '\0';
1320 }
1321
1322 // This function is the stub which is used to turn an ordinary (CNI)
1323 // method call into a JNI call.
1324 void
1325 _Jv_JNIMethod::call (ffi_cif *cif, void *ret, ffi_raw *args, void *__this)
1326 {
1327   _Jv_JNIMethod* _this = (_Jv_JNIMethod *) __this;
1328
1329   JNIEnv env;
1330   _Jv_JNI_LocalFrame *frame
1331     = (_Jv_JNI_LocalFrame *) alloca (sizeof (_Jv_JNI_LocalFrame)
1332                                      + FRAME_SIZE * sizeof (jobject));
1333
1334   env.p = &_Jv_JNIFunctions;
1335   env.ex = NULL;
1336   env.klass = _this->defining_class;
1337   env.locals = frame;
1338
1339   frame->marker = true;
1340   frame->next = NULL;
1341   frame->size = FRAME_SIZE;
1342   for (int i = 0; i < frame->size; ++i)
1343     frame->vec[i] = NULL;
1344
1345   // FIXME: we should mark every reference parameter as a local.  For
1346   // now we assume a conservative GC, and we assume that the
1347   // references are on the stack somewhere.
1348
1349   // We cache the value that we find, of course, but if we don't find
1350   // a value we don't cache that fact -- we might subsequently load a
1351   // library which finds the function in question.
1352   if (_this->function == NULL)
1353     {
1354       char buf[10 + 6 * (_this->self->name->length
1355                          + _this->self->signature->length)];
1356       int long_start;
1357       mangled_name (_this->defining_class, _this->self->name,
1358                     _this->self->signature, buf, &long_start);
1359       char c = buf[long_start];
1360       buf[long_start] = '\0';
1361       _this->function = _Jv_FindSymbolInExecutable (buf);
1362       if (_this->function == NULL)
1363         {
1364           buf[long_start] = c;
1365           _this->function = _Jv_FindSymbolInExecutable (buf);
1366           if (_this->function == NULL)
1367             {
1368               jstring str = JvNewStringUTF (_this->self->name->data);
1369               JvThrow (new java::lang::AbstractMethodError (str));
1370             }
1371         }
1372     }
1373
1374   // The actual call to the JNI function.
1375   // FIXME: if this is a static function we must include the class!
1376   ffi_raw_call (cif, (void (*) (...)) _this->function, ret, args);
1377
1378   do
1379     {
1380       _Jv_JNI_PopLocalFrame (&env, NULL);
1381     }
1382   while (env.locals != frame);
1383
1384   if (env.ex)
1385     JvThrow (env.ex);
1386 }
1387
1388 #endif /* INTERPRETER */
1389
1390 \f
1391
1392 //
1393 // Invocation API.
1394 //
1395
1396 // An internal helper function.
1397 static jint
1398 _Jv_JNI_AttachCurrentThread (JavaVM *, jstring name, void **penv, void *args)
1399 {
1400   JavaVMAttachArgs *attach = reinterpret_cast<JavaVMAttachArgs *> (args);
1401   java::lang::ThreadGroup *group = NULL;
1402
1403   if (attach)
1404     {
1405       // FIXME: do we really want to support 1.1?
1406       if (attach->version != JNI_VERSION_1_2
1407           && attach->version != JNI_VERSION_1_1)
1408         return JNI_EVERSION;
1409
1410       JvAssert ((&ThreadGroupClass)->isInstance (attach->group));
1411       group = reinterpret_cast<java::lang::ThreadGroup *> (attach->group);
1412     }
1413
1414   // Attaching an already-attached thread is a no-op.
1415   if (_Jv_ThreadCurrent () != NULL)
1416     return 0;
1417
1418   JNIEnv *env = (JNIEnv *) _Jv_MallocUnchecked (sizeof (JNIEnv));
1419   if (env == NULL)
1420     return JNI_ERR;
1421   env->p = &_Jv_JNIFunctions;
1422   env->ex = NULL;
1423   env->klass = NULL;
1424   env->locals
1425     = (_Jv_JNI_LocalFrame *) _Jv_MallocUnchecked (sizeof (_Jv_JNI_LocalFrame)
1426                                                   + (FRAME_SIZE
1427                                                      * sizeof (jobject)));
1428   if (env->locals == NULL)
1429     {
1430       _Jv_Free (env);
1431       return JNI_ERR;
1432     }
1433   *penv = reinterpret_cast<void *> (env);
1434
1435   java::lang::Thread *t = new gnu::gcj::jni::NativeThread (group, name);
1436   t = t;                        // Avoid compiler warning.  Eww.
1437   _Jv_SetCurrentJNIEnv (env);
1438
1439   return 0;
1440 }
1441
1442 // This is the one actually used by JNI.
1443 static jint
1444 _Jv_JNI_AttachCurrentThread (JavaVM *vm, void **penv, void *args)
1445 {
1446   return _Jv_JNI_AttachCurrentThread (vm, NULL, penv, args);
1447 }
1448
1449 static jint
1450 _Jv_JNI_DestroyJavaVM (JavaVM *vm)
1451 {
1452   JvAssert (the_vm && vm == the_vm);
1453
1454   JNIEnv *env;
1455   if (_Jv_ThreadCurrent () != NULL)
1456     {
1457       jint r = _Jv_JNI_AttachCurrentThread (vm,
1458                                             JvNewStringLatin1 ("main"),
1459                                             reinterpret_cast<void **> (&env),
1460                                             NULL);
1461       if (r < 0)
1462         return r;
1463     }
1464   else
1465     env = _Jv_GetCurrentJNIEnv ();
1466
1467   _Jv_ThreadWait ();
1468
1469   // Docs say that this always returns an error code.
1470   return JNI_ERR;
1471 }
1472
1473 static jint
1474 _Jv_JNI_DetachCurrentThread (JavaVM *)
1475 {
1476   java::lang::Thread *t = _Jv_ThreadCurrent ();
1477   if (t == NULL)
1478     return JNI_EDETACHED;
1479
1480   // FIXME: we only allow threads attached via AttachCurrentThread to
1481   // be detached.  I have no idea how we could implement detaching
1482   // other threads, given the requirement that we must release all the
1483   // monitors.  That just seems evil.
1484   JvAssert ((&NativeThreadClass)->isInstance (t));
1485
1486   // FIXME: release the monitors.  We'll take this to mean all
1487   // monitors acquired via the JNI interface.  This means we have to
1488   // keep track of them.
1489
1490   gnu::gcj::jni::NativeThread *nt
1491     = reinterpret_cast<gnu::gcj::jni::NativeThread *> (t);
1492   nt->finish ();
1493
1494   return 0;
1495 }
1496
1497 static jint
1498 _Jv_JNI_GetEnv (JavaVM *, void **penv, jint version)
1499 {
1500   if (_Jv_ThreadCurrent () == NULL)
1501     {
1502       *penv = NULL;
1503       return JNI_EDETACHED;
1504     }
1505
1506   // FIXME: do we really want to support 1.1?
1507   if (version != JNI_VERSION_1_2 && version != JNI_VERSION_1_1)
1508     {
1509       *penv = NULL;
1510       return JNI_EVERSION;
1511     }
1512
1513   *penv = (void *) _Jv_GetCurrentJNIEnv ();
1514   return 0;
1515 }
1516
1517 jint
1518 JNI_GetDefaultJavaVMInitArgs (void *args)
1519 {
1520   jint version = * (jint *) args;
1521   // Here we only support 1.2.
1522   if (version != JNI_VERSION_1_2)
1523     return JNI_EVERSION;
1524
1525   JavaVMInitArgs *ia = reinterpret_cast<JavaVMInitArgs *> (args);
1526   ia->version = JNI_VERSION_1_2;
1527   ia->nOptions = 0;
1528   ia->options = NULL;
1529   ia->ignoreUnrecognized = true;
1530
1531   return 0;
1532 }
1533
1534 jint
1535 JNI_CreateJavaVM (JavaVM **vm, void **penv, void *args)
1536 {
1537   JvAssert (! the_vm);
1538   // FIXME: synchronize
1539   JavaVM *nvm = (JavaVM *) _Jv_MallocUnchecked (sizeof (JavaVM));
1540   if (nvm == NULL)
1541     return JNI_ERR;
1542   nvm->functions = &_Jv_JNI_InvokeFunctions;
1543
1544   // Parse the arguments.
1545   if (args != NULL)
1546     {
1547       jint version = * (jint *) args;
1548       // We only support 1.2.
1549       if (version != JNI_VERSION_1_2)
1550         return JNI_EVERSION;
1551       JavaVMInitArgs *ia = reinterpret_cast<JavaVMInitArgs *> (args);
1552       for (int i = 0; i < ia->nOptions; ++i)
1553         {
1554           if (! strcmp (ia->options[i].optionString, "vfprintf")
1555               || ! strcmp (ia->options[i].optionString, "exit")
1556               || ! strcmp (ia->options[i].optionString, "abort"))
1557             {
1558               // We are required to recognize these, but for now we
1559               // don't handle them in any way.  FIXME.
1560               continue;
1561             }
1562           else if (! strncmp (ia->options[i].optionString,
1563                               "-verbose", sizeof ("-verbose") - 1))
1564             {
1565               // We don't do anything with this option either.  We
1566               // might want to make sure the argument is valid, but we
1567               // don't really care all that much for now.
1568               continue;
1569             }
1570           else if (! strncmp (ia->options[i].optionString, "-D", 2))
1571             {
1572               // FIXME.
1573               continue;
1574             }
1575           else if (ia->ignoreUnrecognized)
1576             {
1577               if (ia->options[i].optionString[0] == '_'
1578                   || ! strncmp (ia->options[i].optionString, "-X", 2))
1579                 continue;
1580             }
1581
1582           return JNI_ERR;
1583         }
1584     }
1585
1586   jint r =_Jv_JNI_AttachCurrentThread (nvm, penv, NULL);
1587   if (r < 0)
1588     return r;
1589
1590   the_vm = nvm;
1591   *vm = the_vm;
1592   return 0;
1593 }
1594
1595 jint
1596 JNI_GetCreatedJavaVMs (JavaVM **vm_buffer, jsize buf_len, jsize *n_vms)
1597 {
1598   JvAssert (buf_len > 0);
1599   // We only support a single VM.
1600   if (the_vm != NULL)
1601     {
1602       vm_buffer[0] = the_vm;
1603       *n_vms = 1;
1604     }
1605   else
1606     *n_vms = 0;
1607   return 0;
1608 }
1609
1610 jint
1611 _Jv_JNI_GetJavaVM (JNIEnv *, JavaVM **vm)
1612 {
1613   // FIXME: synchronize
1614   if (! the_vm)
1615     {
1616       JavaVM *nvm = (JavaVM *) _Jv_MallocUnchecked (sizeof (JavaVM));
1617       if (nvm == NULL)
1618         return JNI_ERR;
1619       nvm->functions = &_Jv_JNI_InvokeFunctions;
1620       the_vm = nvm;
1621     }
1622
1623   *vm = the_vm;
1624   return 0;
1625 }
1626
1627 \f
1628
1629 #define NOT_IMPL NULL
1630 #define RESERVED NULL
1631
1632 struct JNINativeInterface _Jv_JNIFunctions =
1633 {
1634   RESERVED,
1635   RESERVED,
1636   RESERVED,
1637   RESERVED,
1638   _Jv_JNI_GetVersion,
1639   _Jv_JNI_DefineClass,
1640   _Jv_JNI_FindClass,
1641   _Jv_JNI_FromReflectedMethod,
1642   _Jv_JNI_FromReflectedField,
1643   _Jv_JNI_ToReflectedMethod,
1644   _Jv_JNI_GetSuperclass,
1645   _Jv_JNI_IsAssignableFrom,
1646   _Jv_JNI_ToReflectedField,
1647   _Jv_JNI_Throw,
1648   _Jv_JNI_ThrowNew,
1649   _Jv_JNI_ExceptionOccurred,
1650   _Jv_JNI_ExceptionDescribe,
1651   _Jv_JNI_ExceptionClear,
1652   _Jv_JNI_FatalError,
1653
1654   _Jv_JNI_PushLocalFrame,
1655   _Jv_JNI_PopLocalFrame,
1656   _Jv_JNI_NewGlobalRef,
1657   _Jv_JNI_DeleteGlobalRef,
1658   _Jv_JNI_DeleteLocalRef,
1659
1660   _Jv_JNI_IsSameObject,
1661
1662   _Jv_JNI_NewLocalRef,
1663   _Jv_JNI_EnsureLocalCapacity,
1664
1665   _Jv_JNI_AllocObject,
1666   _Jv_JNI_NewObject,
1667   _Jv_JNI_NewObjectV,
1668   _Jv_JNI_NewObjectA,
1669   _Jv_JNI_GetObjectClass,
1670   _Jv_JNI_IsInstanceOf,
1671   _Jv_JNI_GetAnyMethodID<false>,
1672
1673   _Jv_JNI_CallMethod<jobject>,
1674   _Jv_JNI_CallMethodV<jobject>,
1675   _Jv_JNI_CallMethodA<jobject>,
1676   _Jv_JNI_CallMethod<jboolean>,
1677   _Jv_JNI_CallMethodV<jboolean>,
1678   _Jv_JNI_CallMethodA<jboolean>,
1679   _Jv_JNI_CallMethod<jbyte>,
1680   _Jv_JNI_CallMethodV<jbyte>,
1681   _Jv_JNI_CallMethodA<jbyte>,
1682   _Jv_JNI_CallMethod<jchar>,
1683   _Jv_JNI_CallMethodV<jchar>,
1684   _Jv_JNI_CallMethodA<jchar>,
1685   _Jv_JNI_CallMethod<jshort>,
1686   _Jv_JNI_CallMethodV<jshort>,
1687   _Jv_JNI_CallMethodA<jshort>,
1688   _Jv_JNI_CallMethod<jint>,
1689   _Jv_JNI_CallMethodV<jint>,
1690   _Jv_JNI_CallMethodA<jint>,
1691   _Jv_JNI_CallMethod<jlong>,
1692   _Jv_JNI_CallMethodV<jlong>,
1693   _Jv_JNI_CallMethodA<jlong>,
1694   _Jv_JNI_CallMethod<jfloat>,
1695   _Jv_JNI_CallMethodV<jfloat>,
1696   _Jv_JNI_CallMethodA<jfloat>,
1697   _Jv_JNI_CallMethod<jdouble>,
1698   _Jv_JNI_CallMethodV<jdouble>,
1699   _Jv_JNI_CallMethodA<jdouble>,
1700   _Jv_JNI_CallVoidMethod,
1701   _Jv_JNI_CallVoidMethodV,
1702   _Jv_JNI_CallVoidMethodA,
1703
1704   // Nonvirtual method invocation functions follow.
1705   _Jv_JNI_CallAnyMethod<jobject, nonvirtual>,
1706   _Jv_JNI_CallAnyMethodV<jobject, nonvirtual>,
1707   _Jv_JNI_CallAnyMethodA<jobject, nonvirtual>,
1708   _Jv_JNI_CallAnyMethod<jboolean, nonvirtual>,
1709   _Jv_JNI_CallAnyMethodV<jboolean, nonvirtual>,
1710   _Jv_JNI_CallAnyMethodA<jboolean, nonvirtual>,
1711   _Jv_JNI_CallAnyMethod<jbyte, nonvirtual>,
1712   _Jv_JNI_CallAnyMethodV<jbyte, nonvirtual>,
1713   _Jv_JNI_CallAnyMethodA<jbyte, nonvirtual>,
1714   _Jv_JNI_CallAnyMethod<jchar, nonvirtual>,
1715   _Jv_JNI_CallAnyMethodV<jchar, nonvirtual>,
1716   _Jv_JNI_CallAnyMethodA<jchar, nonvirtual>,
1717   _Jv_JNI_CallAnyMethod<jshort, nonvirtual>,
1718   _Jv_JNI_CallAnyMethodV<jshort, nonvirtual>,
1719   _Jv_JNI_CallAnyMethodA<jshort, nonvirtual>,
1720   _Jv_JNI_CallAnyMethod<jint, nonvirtual>,
1721   _Jv_JNI_CallAnyMethodV<jint, nonvirtual>,
1722   _Jv_JNI_CallAnyMethodA<jint, nonvirtual>,
1723   _Jv_JNI_CallAnyMethod<jlong, nonvirtual>,
1724   _Jv_JNI_CallAnyMethodV<jlong, nonvirtual>,
1725   _Jv_JNI_CallAnyMethodA<jlong, nonvirtual>,
1726   _Jv_JNI_CallAnyMethod<jfloat, nonvirtual>,
1727   _Jv_JNI_CallAnyMethodV<jfloat, nonvirtual>,
1728   _Jv_JNI_CallAnyMethodA<jfloat, nonvirtual>,
1729   _Jv_JNI_CallAnyMethod<jdouble, nonvirtual>,
1730   _Jv_JNI_CallAnyMethodV<jdouble, nonvirtual>,
1731   _Jv_JNI_CallAnyMethodA<jdouble, nonvirtual>,
1732   _Jv_JNI_CallAnyVoidMethod<nonvirtual>,
1733   _Jv_JNI_CallAnyVoidMethodV<nonvirtual>,
1734   _Jv_JNI_CallAnyVoidMethodA<nonvirtual>,
1735
1736   _Jv_JNI_GetAnyFieldID<false>,
1737   _Jv_JNI_GetField<jobject>,
1738   _Jv_JNI_GetField<jboolean>,
1739   _Jv_JNI_GetField<jbyte>,
1740   _Jv_JNI_GetField<jchar>,
1741   _Jv_JNI_GetField<jshort>,
1742   _Jv_JNI_GetField<jint>,
1743   _Jv_JNI_GetField<jlong>,
1744   _Jv_JNI_GetField<jfloat>,
1745   _Jv_JNI_GetField<jdouble>,
1746   _Jv_JNI_SetField,
1747   _Jv_JNI_SetField,
1748   _Jv_JNI_SetField,
1749   _Jv_JNI_SetField,
1750   _Jv_JNI_SetField,
1751   _Jv_JNI_SetField,
1752   _Jv_JNI_SetField,
1753   _Jv_JNI_SetField,
1754   _Jv_JNI_SetField,
1755   _Jv_JNI_GetAnyMethodID<true>,
1756
1757   _Jv_JNI_CallStaticMethod<jobject>,
1758   _Jv_JNI_CallStaticMethodV<jobject>,
1759   _Jv_JNI_CallStaticMethodA<jobject>,
1760   _Jv_JNI_CallStaticMethod<jboolean>,
1761   _Jv_JNI_CallStaticMethodV<jboolean>,
1762   _Jv_JNI_CallStaticMethodA<jboolean>,
1763   _Jv_JNI_CallStaticMethod<jbyte>,
1764   _Jv_JNI_CallStaticMethodV<jbyte>,
1765   _Jv_JNI_CallStaticMethodA<jbyte>,
1766   _Jv_JNI_CallStaticMethod<jchar>,
1767   _Jv_JNI_CallStaticMethodV<jchar>,
1768   _Jv_JNI_CallStaticMethodA<jchar>,
1769   _Jv_JNI_CallStaticMethod<jshort>,
1770   _Jv_JNI_CallStaticMethodV<jshort>,
1771   _Jv_JNI_CallStaticMethodA<jshort>,
1772   _Jv_JNI_CallStaticMethod<jint>,
1773   _Jv_JNI_CallStaticMethodV<jint>,
1774   _Jv_JNI_CallStaticMethodA<jint>,
1775   _Jv_JNI_CallStaticMethod<jlong>,
1776   _Jv_JNI_CallStaticMethodV<jlong>,
1777   _Jv_JNI_CallStaticMethodA<jlong>,
1778   _Jv_JNI_CallStaticMethod<jfloat>,
1779   _Jv_JNI_CallStaticMethodV<jfloat>,
1780   _Jv_JNI_CallStaticMethodA<jfloat>,
1781   _Jv_JNI_CallStaticMethod<jdouble>,
1782   _Jv_JNI_CallStaticMethodV<jdouble>,
1783   _Jv_JNI_CallStaticMethodA<jdouble>,
1784   _Jv_JNI_CallStaticVoidMethod,
1785   _Jv_JNI_CallStaticVoidMethodV,
1786   _Jv_JNI_CallStaticVoidMethodA,
1787
1788   _Jv_JNI_GetAnyFieldID<true>,
1789   _Jv_JNI_GetStaticField<jobject>,
1790   _Jv_JNI_GetStaticField<jboolean>,
1791   _Jv_JNI_GetStaticField<jbyte>,
1792   _Jv_JNI_GetStaticField<jchar>,
1793   _Jv_JNI_GetStaticField<jshort>,
1794   _Jv_JNI_GetStaticField<jint>,
1795   _Jv_JNI_GetStaticField<jlong>,
1796   _Jv_JNI_GetStaticField<jfloat>,
1797   _Jv_JNI_GetStaticField<jdouble>,
1798   _Jv_JNI_SetStaticField,
1799   _Jv_JNI_SetStaticField,
1800   _Jv_JNI_SetStaticField,
1801   _Jv_JNI_SetStaticField,
1802   _Jv_JNI_SetStaticField,
1803   _Jv_JNI_SetStaticField,
1804   _Jv_JNI_SetStaticField,
1805   _Jv_JNI_SetStaticField,
1806   _Jv_JNI_SetStaticField,
1807   _Jv_JNI_NewString,
1808   _Jv_JNI_GetStringLength,
1809   _Jv_JNI_GetStringChars,
1810   _Jv_JNI_ReleaseStringChars,
1811   _Jv_JNI_NewStringUTF,
1812   _Jv_JNI_GetStringUTFLength,
1813   _Jv_JNI_GetStringUTFChars,
1814   _Jv_JNI_ReleaseStringUTFChars,
1815   _Jv_JNI_GetArrayLength,
1816   _Jv_JNI_NewObjectArray,
1817   _Jv_JNI_GetObjectArrayElement,
1818   _Jv_JNI_SetObjectArrayElement,
1819   _Jv_JNI_NewPrimitiveArray<jboolean, JvPrimClass (boolean)>,
1820   _Jv_JNI_NewPrimitiveArray<jbyte, JvPrimClass (byte)>,
1821   _Jv_JNI_NewPrimitiveArray<jchar, JvPrimClass (char)>,
1822   _Jv_JNI_NewPrimitiveArray<jshort, JvPrimClass (short)>,
1823   _Jv_JNI_NewPrimitiveArray<jint, JvPrimClass (int)>,
1824   _Jv_JNI_NewPrimitiveArray<jlong, JvPrimClass (long)>,
1825   _Jv_JNI_NewPrimitiveArray<jfloat, JvPrimClass (float)>,
1826   _Jv_JNI_NewPrimitiveArray<jdouble, JvPrimClass (double)>,
1827   _Jv_JNI_GetPrimitiveArrayElements,
1828   _Jv_JNI_GetPrimitiveArrayElements,
1829   _Jv_JNI_GetPrimitiveArrayElements,
1830   _Jv_JNI_GetPrimitiveArrayElements,
1831   _Jv_JNI_GetPrimitiveArrayElements,
1832   _Jv_JNI_GetPrimitiveArrayElements,
1833   _Jv_JNI_GetPrimitiveArrayElements,
1834   _Jv_JNI_GetPrimitiveArrayElements,
1835   _Jv_JNI_ReleasePrimitiveArrayElements,
1836   _Jv_JNI_ReleasePrimitiveArrayElements,
1837   _Jv_JNI_ReleasePrimitiveArrayElements,
1838   _Jv_JNI_ReleasePrimitiveArrayElements,
1839   _Jv_JNI_ReleasePrimitiveArrayElements,
1840   _Jv_JNI_ReleasePrimitiveArrayElements,
1841   _Jv_JNI_ReleasePrimitiveArrayElements,
1842   _Jv_JNI_ReleasePrimitiveArrayElements,
1843   _Jv_JNI_GetPrimitiveArrayRegion,
1844   _Jv_JNI_GetPrimitiveArrayRegion,
1845   _Jv_JNI_GetPrimitiveArrayRegion,
1846   _Jv_JNI_GetPrimitiveArrayRegion,
1847   _Jv_JNI_GetPrimitiveArrayRegion,
1848   _Jv_JNI_GetPrimitiveArrayRegion,
1849   _Jv_JNI_GetPrimitiveArrayRegion,
1850   _Jv_JNI_GetPrimitiveArrayRegion,
1851   _Jv_JNI_SetPrimitiveArrayRegion,
1852   _Jv_JNI_SetPrimitiveArrayRegion,
1853   _Jv_JNI_SetPrimitiveArrayRegion,
1854   _Jv_JNI_SetPrimitiveArrayRegion,
1855   _Jv_JNI_SetPrimitiveArrayRegion,
1856   _Jv_JNI_SetPrimitiveArrayRegion,
1857   _Jv_JNI_SetPrimitiveArrayRegion,
1858   _Jv_JNI_SetPrimitiveArrayRegion,
1859   NOT_IMPL /* RegisterNatives */,
1860   NOT_IMPL /* UnregisterNatives */,
1861   _Jv_JNI_MonitorEnter,
1862   _Jv_JNI_MonitorExit,
1863   _Jv_JNI_GetJavaVM,
1864
1865   _Jv_JNI_GetStringRegion,
1866   _Jv_JNI_GetStringUTFRegion,
1867   _Jv_JNI_GetPrimitiveArrayCritical,
1868   _Jv_JNI_ReleasePrimitiveArrayCritical,
1869   _Jv_JNI_GetStringCritical,
1870   _Jv_JNI_ReleaseStringCritical,
1871
1872   NOT_IMPL /* newweakglobalref */,
1873   NOT_IMPL /* deleteweakglobalref */,
1874
1875   _Jv_JNI_ExceptionCheck
1876 };
1877
1878 struct JNIInvokeInterface _Jv_JNI_InvokeFunctions =
1879 {
1880   RESERVED,
1881   RESERVED,
1882   RESERVED,
1883
1884   _Jv_JNI_DestroyJavaVM,
1885   _Jv_JNI_AttachCurrentThread,
1886   _Jv_JNI_DetachCurrentThread,
1887   _Jv_JNI_GetEnv
1888 };