OSDN Git Service

* jni.cc (_Jv_JNI_NewObjectV): Corrected assertion.
[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->loadClass (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   // For constructors we need to pass the Class we are instantiating.
564   if (style == constructor)
565     return_type = klass;
566
567   jvalue result;
568   jthrowable ex = _Jv_CallAnyMethodA (obj, return_type, id,
569                                       style == constructor,
570                                       arg_types, args, &result);
571
572   if (ex != NULL)
573     env->ex = ex;
574
575   // We cheat a little here.  FIXME.
576   return wrap_value (env, * (T *) &result);
577 }
578
579 template<typename T, invocation_type style>
580 static T
581 _Jv_JNI_CallAnyMethod (JNIEnv *env, jobject obj, jclass klass,
582                        jmethodID method, ...)
583 {
584   va_list args;
585   T result;
586
587   va_start (args, method);
588   result = _Jv_JNI_CallAnyMethodV<T, style> (env, obj, klass, method, args);
589   va_end (args);
590
591   return result;
592 }
593
594 template<typename T, invocation_type style>
595 static T
596 _Jv_JNI_CallAnyMethodA (JNIEnv *env, jobject obj, jclass klass,
597                         jmethodID id, jvalue *args)
598 {
599   if (style == normal)
600     id = _Jv_LookupDeclaredMethod (obj->getClass (), id->name, id->signature);
601
602   jclass decl_class = klass ? klass : obj->getClass ();
603   JvAssert (decl_class != NULL);
604
605   jclass return_type;
606   JArray<jclass> *arg_types;
607   // FIXME: exception processing.
608   _Jv_GetTypesFromSignature (id, decl_class,
609                              &arg_types, &return_type);
610
611   // For constructors we need to pass the Class we are instantiating.
612   if (style == constructor)
613     return_type = klass;
614
615   jvalue result;
616   jthrowable ex = _Jv_CallAnyMethodA (obj, return_type, id,
617                                       style == constructor,
618                                       arg_types, args, &result);
619
620   if (ex != NULL)
621     env->ex = ex;
622
623   // We cheat a little here.  FIXME.
624   return wrap_value (env, * (T *) &result);
625 }
626
627 template<invocation_type style>
628 static void
629 _Jv_JNI_CallAnyVoidMethodV (JNIEnv *env, jobject obj, jclass klass,
630                             jmethodID id, va_list vargs)
631 {
632   if (style == normal)
633     id = _Jv_LookupDeclaredMethod (obj->getClass (), id->name, id->signature);
634
635   jclass decl_class = klass ? klass : obj->getClass ();
636   JvAssert (decl_class != NULL);
637
638   jclass return_type;
639   JArray<jclass> *arg_types;
640   // FIXME: exception processing.
641   _Jv_GetTypesFromSignature (id, decl_class,
642                              &arg_types, &return_type);
643
644   jvalue args[arg_types->length];
645   array_from_valist (args, arg_types, vargs);
646
647   // For constructors we need to pass the Class we are instantiating.
648   if (style == constructor)
649     return_type = klass;
650
651   jthrowable ex = _Jv_CallAnyMethodA (obj, return_type, id,
652                                       style == constructor,
653                                       arg_types, args, NULL);
654
655   if (ex != NULL)
656     env->ex = ex;
657 }
658
659 template<invocation_type style>
660 static void
661 _Jv_JNI_CallAnyVoidMethod (JNIEnv *env, jobject obj, jclass klass,
662                            jmethodID method, ...)
663 {
664   va_list args;
665
666   va_start (args, method);
667   _Jv_JNI_CallAnyVoidMethodV<style> (env, obj, klass, method, args);
668   va_end (args);
669 }
670
671 template<invocation_type style>
672 static void
673 _Jv_JNI_CallAnyVoidMethodA (JNIEnv *env, jobject obj, jclass klass,
674                             jmethodID id, jvalue *args)
675 {
676   if (style == normal)
677     id = _Jv_LookupDeclaredMethod (obj->getClass (), id->name, id->signature);
678
679   jclass decl_class = klass ? klass : obj->getClass ();
680   JvAssert (decl_class != NULL);
681
682   jclass return_type;
683   JArray<jclass> *arg_types;
684   // FIXME: exception processing.
685   _Jv_GetTypesFromSignature (id, decl_class,
686                              &arg_types, &return_type);
687
688   jthrowable ex = _Jv_CallAnyMethodA (obj, return_type, id,
689                                       style == constructor,
690                                       arg_types, args, NULL);
691
692   if (ex != NULL)
693     env->ex = ex;
694 }
695
696 // Functions with this signature are used to implement functions in
697 // the CallMethod family.
698 template<typename T>
699 static T
700 _Jv_JNI_CallMethodV (JNIEnv *env, jobject obj, jmethodID id, va_list args)
701 {
702   return _Jv_JNI_CallAnyMethodV<T, normal> (env, obj, NULL, id, args);
703 }
704
705 // Functions with this signature are used to implement functions in
706 // the CallMethod family.
707 template<typename T>
708 static T
709 _Jv_JNI_CallMethod (JNIEnv *env, jobject obj, jmethodID id, ...)
710 {
711   va_list args;
712   T result;
713
714   va_start (args, id);
715   result = _Jv_JNI_CallAnyMethodV<T, normal> (env, obj, NULL, id, args);
716   va_end (args);
717
718   return result;
719 }
720
721 // Functions with this signature are used to implement functions in
722 // the CallMethod family.
723 template<typename T>
724 static T
725 _Jv_JNI_CallMethodA (JNIEnv *env, jobject obj, jmethodID id, jvalue *args)
726 {
727   return _Jv_JNI_CallAnyMethodA<T, normal> (env, obj, NULL, id, args);
728 }
729
730 static void
731 _Jv_JNI_CallVoidMethodV (JNIEnv *env, jobject obj, jmethodID id, va_list args)
732 {
733   _Jv_JNI_CallAnyVoidMethodV<normal> (env, obj, NULL, id, args);
734 }
735
736 static void
737 _Jv_JNI_CallVoidMethod (JNIEnv *env, jobject obj, jmethodID id, ...)
738 {
739   va_list args;
740
741   va_start (args, id);
742   _Jv_JNI_CallAnyVoidMethodV<normal> (env, obj, NULL, id, args);
743   va_end (args);
744 }
745
746 static void
747 _Jv_JNI_CallVoidMethodA (JNIEnv *env, jobject obj, jmethodID id, jvalue *args)
748 {
749   _Jv_JNI_CallAnyVoidMethodA<normal> (env, obj, NULL, id, args);
750 }
751
752 // Functions with this signature are used to implement functions in
753 // the CallStaticMethod family.
754 template<typename T>
755 static T
756 _Jv_JNI_CallStaticMethodV (JNIEnv *env, jclass klass,
757                            jmethodID id, va_list args)
758 {
759   return _Jv_JNI_CallAnyMethodV<T, static_type> (env, NULL, klass, id, args);
760 }
761
762 // Functions with this signature are used to implement functions in
763 // the CallStaticMethod family.
764 template<typename T>
765 static T
766 _Jv_JNI_CallStaticMethod (JNIEnv *env, jclass klass, jmethodID id, ...)
767 {
768   va_list args;
769   T result;
770
771   va_start (args, id);
772   result = _Jv_JNI_CallAnyMethodV<T, static_type> (env, NULL, klass,
773                                                    id, args);
774   va_end (args);
775
776   return result;
777 }
778
779 // Functions with this signature are used to implement functions in
780 // the CallStaticMethod family.
781 template<typename T>
782 static T
783 _Jv_JNI_CallStaticMethodA (JNIEnv *env, jclass klass, jmethodID id,
784                            jvalue *args)
785 {
786   return _Jv_JNI_CallAnyMethodA<T, static_type> (env, NULL, klass, id, args);
787 }
788
789 static void
790 _Jv_JNI_CallStaticVoidMethodV (JNIEnv *env, jclass klass, jmethodID id,
791                                va_list args)
792 {
793   _Jv_JNI_CallAnyVoidMethodV<static_type> (env, NULL, klass, id, args);
794 }
795
796 static void
797 _Jv_JNI_CallStaticVoidMethod (JNIEnv *env, jclass klass, jmethodID id, ...)
798 {
799   va_list args;
800
801   va_start (args, id);
802   _Jv_JNI_CallAnyVoidMethodV<static_type> (env, NULL, klass, id, args);
803   va_end (args);
804 }
805
806 static void
807 _Jv_JNI_CallStaticVoidMethodA (JNIEnv *env, jclass klass, jmethodID id,
808                                jvalue *args)
809 {
810   _Jv_JNI_CallAnyVoidMethodA<static_type> (env, NULL, klass, id, args);
811 }
812
813 static jobject
814 _Jv_JNI_NewObjectV (JNIEnv *env, jclass klass,
815                     jmethodID id, va_list args)
816 {
817   JvAssert (klass && ! klass->isArray ());
818   JvAssert (! strcmp (id->name->data, "<init>")
819             && id->signature->length > 2
820             && id->signature->data[0] == '('
821             && ! strcmp (&id->signature->data[id->signature->length - 2],
822                          ")V"));
823
824   return _Jv_JNI_CallAnyMethodV<jobject, constructor> (env, NULL, klass,
825                                                        id, args);
826 }
827
828 static jobject
829 _Jv_JNI_NewObject (JNIEnv *env, jclass klass, jmethodID id, ...)
830 {
831   JvAssert (klass && ! klass->isArray ());
832   JvAssert (! strcmp (id->name->data, "<init>")
833             && id->signature->length > 2
834             && id->signature->data[0] == '('
835             && ! strcmp (&id->signature->data[id->signature->length - 2],
836                          ")V"));
837
838   va_list args;
839   jobject result;
840
841   va_start (args, id);
842   result = _Jv_JNI_CallAnyMethodV<jobject, constructor> (env, NULL, klass,
843                                                          id, args);
844   va_end (args);
845
846   return result;
847 }
848
849 static jobject
850 _Jv_JNI_NewObjectA (JNIEnv *env, jclass klass, jmethodID id,
851                     jvalue *args)
852 {
853   JvAssert (klass && ! klass->isArray ());
854   JvAssert (! strcmp (id->name->data, "<init>")
855             && id->signature->length > 2
856             && id->signature->data[0] == '('
857             && ! strcmp (&id->signature->data[id->signature->length - 2],
858                          ")V"));
859
860   return _Jv_JNI_CallAnyMethodA<jobject, constructor> (env, NULL, klass,
861                                                        id, args);
862 }
863
864 \f
865
866 template<typename T>
867 static T
868 _Jv_JNI_GetField (JNIEnv *env, jobject obj, jfieldID field) 
869 {
870   JvAssert (obj);
871   T *ptr = (T *) ((char *) obj + field->getOffset ());
872   return wrap_value (env, *ptr);
873 }
874
875 template<typename T>
876 static void
877 _Jv_JNI_SetField (JNIEnv *, jobject obj, jfieldID field, T value)
878 {
879   JvAssert (obj);
880   T *ptr = (T *) ((char *) obj + field->getOffset ());
881   *ptr = value;
882 }
883
884 template<jboolean is_static>
885 static jfieldID
886 _Jv_JNI_GetAnyFieldID (JNIEnv *env, jclass clazz,
887                        const char *name, const char *sig)
888 {
889   // FIXME: exception processing.
890   _Jv_InitClass (clazz);
891
892   _Jv_Utf8Const *a_name = _Jv_makeUtf8Const ((char *) name, -1);
893
894   jclass field_class = NULL;
895   if (sig[0] == '[')
896     field_class = _Jv_FindClassFromSignature ((char *) sig, NULL);
897   else
898     {
899       _Jv_Utf8Const *sig_u = _Jv_makeUtf8Const ((char *) sig, -1);
900       field_class = _Jv_FindClass (sig_u, NULL);
901     }
902
903   // FIXME: what if field_class == NULL?
904
905   while (clazz != NULL)
906     {
907       jint count = (is_static
908                     ? JvNumStaticFields (clazz)
909                     : JvNumInstanceFields (clazz));
910       jfieldID field = (is_static
911                         ? JvGetFirstStaticField (clazz)
912                         : JvGetFirstInstanceField (clazz));
913       for (jint i = 0; i < count; ++i)
914         {
915           // The field is resolved as a side effect of class
916           // initialization.
917           JvAssert (field->isResolved ());
918
919           _Jv_Utf8Const *f_name = field->getNameUtf8Const(clazz);
920
921           if (_Jv_equalUtf8Consts (f_name, a_name)
922               && field->getClass() == field_class)
923             return field;
924
925           field = field->getNextField ();
926         }
927
928       clazz = clazz->getSuperclass ();
929     }
930
931   env->ex = new java::lang::NoSuchFieldError ();
932   return NULL;
933 }
934
935 template<typename T>
936 static T
937 _Jv_JNI_GetStaticField (JNIEnv *env, jclass, jfieldID field)
938 {
939   T *ptr = (T *) field->u.addr;
940   return wrap_value (env, *ptr);
941 }
942
943 template<typename T>
944 static void
945 _Jv_JNI_SetStaticField (JNIEnv *, jclass, jfieldID field, T value)
946 {
947   T *ptr = (T *) field->u.addr;
948   *ptr = value;
949 }
950
951 static jstring
952 _Jv_JNI_NewString (JNIEnv *env, const jchar *unichars, jsize len)
953 {
954   // FIXME: exception processing.
955   jstring r = _Jv_NewString (unichars, len);
956   return (jstring) wrap_value (env, r);
957 }
958
959 static jsize
960 _Jv_JNI_GetStringLength (JNIEnv *, jstring string)
961 {
962   return string->length();
963 }
964
965 static const jchar *
966 _Jv_JNI_GetStringChars (JNIEnv *, jstring string, jboolean *isCopy)
967 {
968   jchar *result = _Jv_GetStringChars (string);
969   mark_for_gc (string);
970   if (isCopy)
971     *isCopy = false;
972   return (const jchar *) result;
973 }
974
975 static void
976 _Jv_JNI_ReleaseStringChars (JNIEnv *, jstring string, const jchar *)
977 {
978   unmark_for_gc (string);
979 }
980
981 static jstring
982 _Jv_JNI_NewStringUTF (JNIEnv *env, const char *bytes)
983 {
984   // FIXME: exception processing.
985   jstring result = JvNewStringUTF (bytes);
986   return (jstring) wrap_value (env, result);
987 }
988
989 static jsize
990 _Jv_JNI_GetStringUTFLength (JNIEnv *, jstring string)
991 {
992   return JvGetStringUTFLength (string);
993 }
994
995 static const char *
996 _Jv_JNI_GetStringUTFChars (JNIEnv *, jstring string, jboolean *isCopy)
997 {
998   jsize len = JvGetStringUTFLength (string);
999   // FIXME: exception processing.
1000   char *r = (char *) _Jv_Malloc (len + 1);
1001   JvGetStringUTFRegion (string, 0, len, r);
1002   r[len] = '\0';
1003
1004   if (isCopy)
1005     *isCopy = true;
1006
1007   return (const char *) r;
1008 }
1009
1010 static void
1011 _Jv_JNI_ReleaseStringUTFChars (JNIEnv *, jstring, const char *utf)
1012 {
1013   _Jv_Free ((void *) utf);
1014 }
1015
1016 static void
1017 _Jv_JNI_GetStringRegion (JNIEnv *env, jstring string, jsize start, jsize len,
1018                          jchar *buf)
1019 {
1020   jchar *result = _Jv_GetStringChars (string);
1021   if (start < 0 || start > string->length ()
1022       || len < 0 || start + len > string->length ())
1023     env->ex = new java::lang::StringIndexOutOfBoundsException ();
1024   else
1025     memcpy (buf, &result[start], len * sizeof (jchar));
1026 }
1027
1028 static void
1029 _Jv_JNI_GetStringUTFRegion (JNIEnv *env, jstring str, jsize start,
1030                             jsize len, char *buf)
1031 {
1032   if (start < 0 || start > str->length ()
1033       || len < 0 || start + len > str->length ())
1034     env->ex = new java::lang::StringIndexOutOfBoundsException ();
1035   else
1036     _Jv_GetStringUTFRegion (str, start, len, buf);
1037 }
1038
1039 static const jchar *
1040 _Jv_JNI_GetStringCritical (JNIEnv *, jstring str, jboolean *isCopy)
1041 {
1042   jchar *result = _Jv_GetStringChars (str);
1043   if (isCopy)
1044     *isCopy = false;
1045   return result;
1046 }
1047
1048 static void
1049 _Jv_JNI_ReleaseStringCritical (JNIEnv *, jstring, const jchar *)
1050 {
1051   // Nothing.
1052 }
1053
1054 static jsize
1055 _Jv_JNI_GetArrayLength (JNIEnv *, jarray array)
1056 {
1057   return array->length;
1058 }
1059
1060 static jarray
1061 _Jv_JNI_NewObjectArray (JNIEnv *env, jsize length, jclass elementClass,
1062                         jobject init)
1063 {
1064   // FIXME: exception processing.
1065   jarray result = JvNewObjectArray (length, elementClass, init);
1066   return (jarray) wrap_value (env, result);
1067 }
1068
1069 static jobject
1070 _Jv_JNI_GetObjectArrayElement (JNIEnv *env, jobjectArray array, jsize index)
1071 {
1072   jobject *elts = elements (array);
1073   return wrap_value (env, elts[index]);
1074 }
1075
1076 static void
1077 _Jv_JNI_SetObjectArrayElement (JNIEnv *, jobjectArray array, jsize index,
1078                                jobject value)
1079 {
1080   // FIXME: exception processing.
1081   _Jv_CheckArrayStore (array, value);
1082   jobject *elts = elements (array);
1083   elts[index] = value;
1084 }
1085
1086 template<typename T, jclass K>
1087 static JArray<T> *
1088 _Jv_JNI_NewPrimitiveArray (JNIEnv *env, jsize length)
1089 {
1090   // FIXME: exception processing.
1091   return (JArray<T> *) wrap_value (env, _Jv_NewPrimArray (K, length));
1092 }
1093
1094 template<typename T>
1095 static T *
1096 _Jv_JNI_GetPrimitiveArrayElements (JNIEnv *, JArray<T> *array,
1097                                    jboolean *isCopy)
1098 {
1099   T *elts = elements (array);
1100   if (isCopy)
1101     {
1102       // We elect never to copy.
1103       *isCopy = false;
1104     }
1105   mark_for_gc (array);
1106   return elts;
1107 }
1108
1109 template<typename T>
1110 static void
1111 _Jv_JNI_ReleasePrimitiveArrayElements (JNIEnv *, JArray<T> *array,
1112                                        T *, jint /* mode */)
1113 {
1114   // Note that we ignore MODE.  We can do this because we never copy
1115   // the array elements.  My reading of the JNI documentation is that
1116   // this is an option for the implementor.
1117   unmark_for_gc (array);
1118 }
1119
1120 template<typename T>
1121 static void
1122 _Jv_JNI_GetPrimitiveArrayRegion (JNIEnv *env, JArray<T> *array,
1123                                  jsize start, jsize len,
1124                                  T *buf)
1125 {
1126   if (start < 0 || len >= array->length || start + len >= array->length)
1127     {
1128       // FIXME: index.
1129       env->ex = new java::lang::ArrayIndexOutOfBoundsException ();
1130     }
1131   else
1132     {
1133       T *elts = elements (array) + start;
1134       memcpy (buf, elts, len * sizeof (T));
1135     }
1136 }
1137
1138 template<typename T>
1139 static void
1140 _Jv_JNI_SetPrimitiveArrayRegion (JNIEnv *env, JArray<T> *array, 
1141                                  jsize start, jsize len, T *buf)
1142 {
1143   if (start < 0 || len >= array->length || start + len >= array->length)
1144     {
1145       // FIXME: index.
1146       env->ex = new java::lang::ArrayIndexOutOfBoundsException ();
1147     }
1148   else
1149     {
1150       T *elts = elements (array) + start;
1151       memcpy (elts, buf, len * sizeof (T));
1152     }
1153 }
1154
1155 static void *
1156 _Jv_JNI_GetPrimitiveArrayCritical (JNIEnv *, jarray array,
1157                                    jboolean *isCopy)
1158 {
1159   // FIXME: does this work?
1160   jclass klass = array->getClass()->getComponentType();
1161   JvAssert (klass->isPrimitive ());
1162   char *r = _Jv_GetArrayElementFromElementType (array, klass);
1163   if (isCopy)
1164     *isCopy = false;
1165   return r;
1166 }
1167
1168 static void
1169 _Jv_JNI_ReleasePrimitiveArrayCritical (JNIEnv *, jarray, void *, jint)
1170 {
1171   // Nothing.
1172 }
1173
1174 static jint
1175 _Jv_JNI_MonitorEnter (JNIEnv *, jobject obj)
1176 {
1177   // FIXME: exception processing.
1178   jint r = _Jv_MonitorEnter (obj);
1179   return r;
1180 }
1181
1182 static jint
1183 _Jv_JNI_MonitorExit (JNIEnv *, jobject obj)
1184 {
1185   // FIXME: exception processing.
1186   jint r = _Jv_MonitorExit (obj);
1187   return r;
1188 }
1189
1190 // JDK 1.2
1191 jobject
1192 _Jv_JNI_ToReflectedField (JNIEnv *env, jclass cls, jfieldID fieldID,
1193                           jboolean)
1194 {
1195   // FIXME: exception processing.
1196   java::lang::reflect::Field *field = new java::lang::reflect::Field();
1197   field->declaringClass = cls;
1198   field->offset = (char*) fieldID - (char *) cls->fields;
1199   field->name = _Jv_NewStringUtf8Const (fieldID->getNameUtf8Const (cls));
1200   return wrap_value (env, field);
1201 }
1202
1203 // JDK 1.2
1204 static jfieldID
1205 _Jv_JNI_FromReflectedField (JNIEnv *, jobject f)
1206 {
1207   using namespace java::lang::reflect;
1208
1209   Field *field = reinterpret_cast<Field *> (f);
1210   return _Jv_FromReflectedField (field);
1211 }
1212
1213 jobject
1214 _Jv_JNI_ToReflectedMethod (JNIEnv *env, jclass klass, jmethodID id,
1215                            jboolean)
1216 {
1217   using namespace java::lang::reflect;
1218
1219   // FIXME.
1220   static _Jv_Utf8Const *init_name = _Jv_makeUtf8Const ("<init>", 6);
1221
1222   jobject result;
1223   if (_Jv_equalUtf8Consts (id->name, init_name))
1224     {
1225       // A constructor.
1226       Constructor *cons = new Constructor ();
1227       cons->offset = (char *) id - (char *) &klass->methods;
1228       cons->declaringClass = klass;
1229       result = cons;
1230     }
1231   else
1232     {
1233       Method *meth = new Method ();
1234       meth->offset = (char *) id - (char *) &klass->methods;
1235       meth->declaringClass = klass;
1236       result = meth;
1237     }
1238
1239   return wrap_value (env, result);
1240 }
1241
1242 static jmethodID
1243 _Jv_JNI_FromReflectedMethod (JNIEnv *, jobject method)
1244 {
1245   using namespace java::lang::reflect;
1246   if ((&MethodClass)->isInstance (method))
1247     return _Jv_FromReflectedMethod (reinterpret_cast<Method *> (method));
1248   return
1249     _Jv_FromReflectedConstructor (reinterpret_cast<Constructor *> (method));
1250 }
1251
1252 \f
1253
1254 #ifdef INTERPRETER
1255
1256 // Add a character to the buffer, encoding properly.
1257 static void
1258 add_char (char *buf, jchar c, int *here)
1259 {
1260   if (c == '_')
1261     {
1262       buf[(*here)++] = '_';
1263       buf[(*here)++] = '1';
1264     }
1265   else if (c == ';')
1266     {
1267       buf[(*here)++] = '_';
1268       buf[(*here)++] = '2';
1269     }
1270   else if (c == '[')
1271     {
1272       buf[(*here)++] = '_';
1273       buf[(*here)++] = '3';
1274     }
1275   else if (c == '/')
1276     buf[(*here)++] = '_';
1277   else if ((c >= '0' && c <= '9')
1278       || (c >= 'a' && c <= 'z')
1279       || (c >= 'A' && c <= 'Z'))
1280     buf[(*here)++] = (char) c;
1281   else
1282     {
1283       // "Unicode" character.
1284       buf[(*here)++] = '_';
1285       buf[(*here)++] = '0';
1286       for (int i = 0; i < 4; ++i)
1287         {
1288           int val = c & 0x0f;
1289           buf[(*here) + 4 - i] = (val > 10) ? ('a' + val - 10) : ('0' + val);
1290           c >>= 4;
1291         }
1292       *here += 4;
1293     }
1294 }
1295
1296 // Compute a mangled name for a native function.  This computes the
1297 // long name, and also returns an index which indicates where a NUL
1298 // can be placed to create the short name.  This function assumes that
1299 // the buffer is large enough for its results.
1300 static void
1301 mangled_name (jclass klass, _Jv_Utf8Const *func_name,
1302               _Jv_Utf8Const *signature, char *buf, int *long_start)
1303 {
1304   strcpy (buf, "Java_");
1305   int here = 5;
1306
1307   // Add fully qualified class name.
1308   jchar *chars = _Jv_GetStringChars (klass->getName ());
1309   jint len = klass->getName ()->length ();
1310   for (int i = 0; i < len; ++i)
1311     add_char (buf, chars[i], &here);
1312
1313   // Don't use add_char because we need a literal `_'.
1314   buf[here++] = '_';
1315
1316   const unsigned char *fn = (const unsigned char *) func_name->data;
1317   const unsigned char *limit = fn + func_name->length;
1318   for (int i = 0; ; ++i)
1319     {
1320       int ch = UTF8_GET (fn, limit);
1321       if (ch < 0)
1322         break;
1323       add_char (buf, ch, &here);
1324     }
1325
1326   // This is where the long signature begins.
1327   *long_start = here;
1328   buf[here++] = '_';
1329   buf[here++] = '_';
1330
1331   const unsigned char *sig = (const unsigned char *) signature->data;
1332   limit = sig + signature->length;
1333   JvAssert (signature[0] == '(');
1334   ++sig;
1335   while (1)
1336     {
1337       int ch = UTF8_GET (sig, limit);
1338       if (ch == ')' || ch < 0)
1339         break;
1340       add_char (buf, ch, &here);
1341     }
1342
1343   buf[here] = '\0';
1344 }
1345
1346 // This function is the stub which is used to turn an ordinary (CNI)
1347 // method call into a JNI call.
1348 void
1349 _Jv_JNIMethod::call (ffi_cif *, void *ret, ffi_raw *args, void *__this)
1350 {
1351   _Jv_JNIMethod* _this = (_Jv_JNIMethod *) __this;
1352
1353   JNIEnv env;
1354   _Jv_JNI_LocalFrame *frame
1355     = (_Jv_JNI_LocalFrame *) alloca (sizeof (_Jv_JNI_LocalFrame)
1356                                      + FRAME_SIZE * sizeof (jobject));
1357
1358   env.p = &_Jv_JNIFunctions;
1359   env.ex = NULL;
1360   env.klass = _this->defining_class;
1361   env.locals = frame;
1362
1363   frame->marker = true;
1364   frame->next = NULL;
1365   frame->size = FRAME_SIZE;
1366   for (int i = 0; i < frame->size; ++i)
1367     frame->vec[i] = NULL;
1368
1369   // FIXME: we should mark every reference parameter as a local.  For
1370   // now we assume a conservative GC, and we assume that the
1371   // references are on the stack somewhere.
1372
1373   // We cache the value that we find, of course, but if we don't find
1374   // a value we don't cache that fact -- we might subsequently load a
1375   // library which finds the function in question.
1376   if (_this->function == NULL)
1377     {
1378       char buf[10 + 6 * (_this->self->name->length
1379                          + _this->self->signature->length)];
1380       int long_start;
1381       mangled_name (_this->defining_class, _this->self->name,
1382                     _this->self->signature, buf, &long_start);
1383       char c = buf[long_start];
1384       buf[long_start] = '\0';
1385       _this->function = _Jv_FindSymbolInExecutable (buf);
1386       if (_this->function == NULL)
1387         {
1388           buf[long_start] = c;
1389           _this->function = _Jv_FindSymbolInExecutable (buf);
1390           if (_this->function == NULL)
1391             {
1392               jstring str = JvNewStringUTF (_this->self->name->data);
1393               JvThrow (new java::lang::AbstractMethodError (str));
1394             }
1395         }
1396     }
1397
1398   JvAssert (_this->args_raw_size % sizeof (ffi_raw) == 0);
1399   ffi_raw real_args[2 + _this->args_raw_size / sizeof (ffi_raw)];
1400   int offset = 0;
1401
1402   // First argument is always the environment pointer.
1403   real_args[offset++].ptr = &env;
1404
1405   // For a static method, we pass in the Class.  For non-static
1406   // methods, the `this' argument is already handled.
1407   if ((_this->self->accflags & java::lang::reflect::Modifier::STATIC))
1408     real_args[offset++].ptr = _this->defining_class;
1409
1410   // Copy over passed-in arguments.
1411   memcpy (&real_args[offset], args, _this->args_raw_size);
1412
1413   // The actual call to the JNI function.
1414   ffi_raw_call (&_this->jni_cif, (void (*) (...)) _this->function,
1415                 ret, real_args);
1416
1417   do
1418     {
1419       _Jv_JNI_PopLocalFrame (&env, NULL);
1420     }
1421   while (env.locals != frame);
1422
1423   if (env.ex)
1424     JvThrow (env.ex);
1425 }
1426
1427 #endif /* INTERPRETER */
1428
1429 \f
1430
1431 //
1432 // Invocation API.
1433 //
1434
1435 // An internal helper function.
1436 static jint
1437 _Jv_JNI_AttachCurrentThread (JavaVM *, jstring name, void **penv, void *args)
1438 {
1439   JavaVMAttachArgs *attach = reinterpret_cast<JavaVMAttachArgs *> (args);
1440   java::lang::ThreadGroup *group = NULL;
1441
1442   if (attach)
1443     {
1444       // FIXME: do we really want to support 1.1?
1445       if (attach->version != JNI_VERSION_1_2
1446           && attach->version != JNI_VERSION_1_1)
1447         return JNI_EVERSION;
1448
1449       JvAssert ((&ThreadGroupClass)->isInstance (attach->group));
1450       group = reinterpret_cast<java::lang::ThreadGroup *> (attach->group);
1451     }
1452
1453   // Attaching an already-attached thread is a no-op.
1454   if (_Jv_ThreadCurrent () != NULL)
1455     return 0;
1456
1457   JNIEnv *env = (JNIEnv *) _Jv_MallocUnchecked (sizeof (JNIEnv));
1458   if (env == NULL)
1459     return JNI_ERR;
1460   env->p = &_Jv_JNIFunctions;
1461   env->ex = NULL;
1462   env->klass = NULL;
1463   env->locals
1464     = (_Jv_JNI_LocalFrame *) _Jv_MallocUnchecked (sizeof (_Jv_JNI_LocalFrame)
1465                                                   + (FRAME_SIZE
1466                                                      * sizeof (jobject)));
1467   if (env->locals == NULL)
1468     {
1469       _Jv_Free (env);
1470       return JNI_ERR;
1471     }
1472   *penv = reinterpret_cast<void *> (env);
1473
1474   java::lang::Thread *t = new gnu::gcj::jni::NativeThread (group, name);
1475   t = t;                        // Avoid compiler warning.  Eww.
1476   _Jv_SetCurrentJNIEnv (env);
1477
1478   return 0;
1479 }
1480
1481 // This is the one actually used by JNI.
1482 static jint
1483 _Jv_JNI_AttachCurrentThread (JavaVM *vm, void **penv, void *args)
1484 {
1485   return _Jv_JNI_AttachCurrentThread (vm, NULL, penv, args);
1486 }
1487
1488 static jint
1489 _Jv_JNI_DestroyJavaVM (JavaVM *vm)
1490 {
1491   JvAssert (the_vm && vm == the_vm);
1492
1493   JNIEnv *env;
1494   if (_Jv_ThreadCurrent () != NULL)
1495     {
1496       jint r = _Jv_JNI_AttachCurrentThread (vm,
1497                                             JvNewStringLatin1 ("main"),
1498                                             reinterpret_cast<void **> (&env),
1499                                             NULL);
1500       if (r < 0)
1501         return r;
1502     }
1503   else
1504     env = _Jv_GetCurrentJNIEnv ();
1505
1506   _Jv_ThreadWait ();
1507
1508   // Docs say that this always returns an error code.
1509   return JNI_ERR;
1510 }
1511
1512 static jint
1513 _Jv_JNI_DetachCurrentThread (JavaVM *)
1514 {
1515   java::lang::Thread *t = _Jv_ThreadCurrent ();
1516   if (t == NULL)
1517     return JNI_EDETACHED;
1518
1519   // FIXME: we only allow threads attached via AttachCurrentThread to
1520   // be detached.  I have no idea how we could implement detaching
1521   // other threads, given the requirement that we must release all the
1522   // monitors.  That just seems evil.
1523   JvAssert ((&NativeThreadClass)->isInstance (t));
1524
1525   // FIXME: release the monitors.  We'll take this to mean all
1526   // monitors acquired via the JNI interface.  This means we have to
1527   // keep track of them.
1528
1529   gnu::gcj::jni::NativeThread *nt
1530     = reinterpret_cast<gnu::gcj::jni::NativeThread *> (t);
1531   nt->finish ();
1532
1533   return 0;
1534 }
1535
1536 static jint
1537 _Jv_JNI_GetEnv (JavaVM *, void **penv, jint version)
1538 {
1539   if (_Jv_ThreadCurrent () == NULL)
1540     {
1541       *penv = NULL;
1542       return JNI_EDETACHED;
1543     }
1544
1545   // FIXME: do we really want to support 1.1?
1546   if (version != JNI_VERSION_1_2 && version != JNI_VERSION_1_1)
1547     {
1548       *penv = NULL;
1549       return JNI_EVERSION;
1550     }
1551
1552   *penv = (void *) _Jv_GetCurrentJNIEnv ();
1553   return 0;
1554 }
1555
1556 jint
1557 JNI_GetDefaultJavaVMInitArgs (void *args)
1558 {
1559   jint version = * (jint *) args;
1560   // Here we only support 1.2.
1561   if (version != JNI_VERSION_1_2)
1562     return JNI_EVERSION;
1563
1564   JavaVMInitArgs *ia = reinterpret_cast<JavaVMInitArgs *> (args);
1565   ia->version = JNI_VERSION_1_2;
1566   ia->nOptions = 0;
1567   ia->options = NULL;
1568   ia->ignoreUnrecognized = true;
1569
1570   return 0;
1571 }
1572
1573 jint
1574 JNI_CreateJavaVM (JavaVM **vm, void **penv, void *args)
1575 {
1576   JvAssert (! the_vm);
1577   // FIXME: synchronize
1578   JavaVM *nvm = (JavaVM *) _Jv_MallocUnchecked (sizeof (JavaVM));
1579   if (nvm == NULL)
1580     return JNI_ERR;
1581   nvm->functions = &_Jv_JNI_InvokeFunctions;
1582
1583   // Parse the arguments.
1584   if (args != NULL)
1585     {
1586       jint version = * (jint *) args;
1587       // We only support 1.2.
1588       if (version != JNI_VERSION_1_2)
1589         return JNI_EVERSION;
1590       JavaVMInitArgs *ia = reinterpret_cast<JavaVMInitArgs *> (args);
1591       for (int i = 0; i < ia->nOptions; ++i)
1592         {
1593           if (! strcmp (ia->options[i].optionString, "vfprintf")
1594               || ! strcmp (ia->options[i].optionString, "exit")
1595               || ! strcmp (ia->options[i].optionString, "abort"))
1596             {
1597               // We are required to recognize these, but for now we
1598               // don't handle them in any way.  FIXME.
1599               continue;
1600             }
1601           else if (! strncmp (ia->options[i].optionString,
1602                               "-verbose", sizeof ("-verbose") - 1))
1603             {
1604               // We don't do anything with this option either.  We
1605               // might want to make sure the argument is valid, but we
1606               // don't really care all that much for now.
1607               continue;
1608             }
1609           else if (! strncmp (ia->options[i].optionString, "-D", 2))
1610             {
1611               // FIXME.
1612               continue;
1613             }
1614           else if (ia->ignoreUnrecognized)
1615             {
1616               if (ia->options[i].optionString[0] == '_'
1617                   || ! strncmp (ia->options[i].optionString, "-X", 2))
1618                 continue;
1619             }
1620
1621           return JNI_ERR;
1622         }
1623     }
1624
1625   jint r =_Jv_JNI_AttachCurrentThread (nvm, penv, NULL);
1626   if (r < 0)
1627     return r;
1628
1629   the_vm = nvm;
1630   *vm = the_vm;
1631   return 0;
1632 }
1633
1634 jint
1635 JNI_GetCreatedJavaVMs (JavaVM **vm_buffer, jsize buf_len, jsize *n_vms)
1636 {
1637   JvAssert (buf_len > 0);
1638   // We only support a single VM.
1639   if (the_vm != NULL)
1640     {
1641       vm_buffer[0] = the_vm;
1642       *n_vms = 1;
1643     }
1644   else
1645     *n_vms = 0;
1646   return 0;
1647 }
1648
1649 jint
1650 _Jv_JNI_GetJavaVM (JNIEnv *, JavaVM **vm)
1651 {
1652   // FIXME: synchronize
1653   if (! the_vm)
1654     {
1655       JavaVM *nvm = (JavaVM *) _Jv_MallocUnchecked (sizeof (JavaVM));
1656       if (nvm == NULL)
1657         return JNI_ERR;
1658       nvm->functions = &_Jv_JNI_InvokeFunctions;
1659       the_vm = nvm;
1660     }
1661
1662   *vm = the_vm;
1663   return 0;
1664 }
1665
1666 \f
1667
1668 #define NOT_IMPL NULL
1669 #define RESERVED NULL
1670
1671 struct JNINativeInterface _Jv_JNIFunctions =
1672 {
1673   RESERVED,
1674   RESERVED,
1675   RESERVED,
1676   RESERVED,
1677   _Jv_JNI_GetVersion,
1678   _Jv_JNI_DefineClass,
1679   _Jv_JNI_FindClass,
1680   _Jv_JNI_FromReflectedMethod,
1681   _Jv_JNI_FromReflectedField,
1682   _Jv_JNI_ToReflectedMethod,
1683   _Jv_JNI_GetSuperclass,
1684   _Jv_JNI_IsAssignableFrom,
1685   _Jv_JNI_ToReflectedField,
1686   _Jv_JNI_Throw,
1687   _Jv_JNI_ThrowNew,
1688   _Jv_JNI_ExceptionOccurred,
1689   _Jv_JNI_ExceptionDescribe,
1690   _Jv_JNI_ExceptionClear,
1691   _Jv_JNI_FatalError,
1692
1693   _Jv_JNI_PushLocalFrame,
1694   _Jv_JNI_PopLocalFrame,
1695   _Jv_JNI_NewGlobalRef,
1696   _Jv_JNI_DeleteGlobalRef,
1697   _Jv_JNI_DeleteLocalRef,
1698
1699   _Jv_JNI_IsSameObject,
1700
1701   _Jv_JNI_NewLocalRef,
1702   _Jv_JNI_EnsureLocalCapacity,
1703
1704   _Jv_JNI_AllocObject,
1705   _Jv_JNI_NewObject,
1706   _Jv_JNI_NewObjectV,
1707   _Jv_JNI_NewObjectA,
1708   _Jv_JNI_GetObjectClass,
1709   _Jv_JNI_IsInstanceOf,
1710   _Jv_JNI_GetAnyMethodID<false>,
1711
1712   _Jv_JNI_CallMethod<jobject>,
1713   _Jv_JNI_CallMethodV<jobject>,
1714   _Jv_JNI_CallMethodA<jobject>,
1715   _Jv_JNI_CallMethod<jboolean>,
1716   _Jv_JNI_CallMethodV<jboolean>,
1717   _Jv_JNI_CallMethodA<jboolean>,
1718   _Jv_JNI_CallMethod<jbyte>,
1719   _Jv_JNI_CallMethodV<jbyte>,
1720   _Jv_JNI_CallMethodA<jbyte>,
1721   _Jv_JNI_CallMethod<jchar>,
1722   _Jv_JNI_CallMethodV<jchar>,
1723   _Jv_JNI_CallMethodA<jchar>,
1724   _Jv_JNI_CallMethod<jshort>,
1725   _Jv_JNI_CallMethodV<jshort>,
1726   _Jv_JNI_CallMethodA<jshort>,
1727   _Jv_JNI_CallMethod<jint>,
1728   _Jv_JNI_CallMethodV<jint>,
1729   _Jv_JNI_CallMethodA<jint>,
1730   _Jv_JNI_CallMethod<jlong>,
1731   _Jv_JNI_CallMethodV<jlong>,
1732   _Jv_JNI_CallMethodA<jlong>,
1733   _Jv_JNI_CallMethod<jfloat>,
1734   _Jv_JNI_CallMethodV<jfloat>,
1735   _Jv_JNI_CallMethodA<jfloat>,
1736   _Jv_JNI_CallMethod<jdouble>,
1737   _Jv_JNI_CallMethodV<jdouble>,
1738   _Jv_JNI_CallMethodA<jdouble>,
1739   _Jv_JNI_CallVoidMethod,
1740   _Jv_JNI_CallVoidMethodV,
1741   _Jv_JNI_CallVoidMethodA,
1742
1743   // Nonvirtual method invocation functions follow.
1744   _Jv_JNI_CallAnyMethod<jobject, nonvirtual>,
1745   _Jv_JNI_CallAnyMethodV<jobject, nonvirtual>,
1746   _Jv_JNI_CallAnyMethodA<jobject, nonvirtual>,
1747   _Jv_JNI_CallAnyMethod<jboolean, nonvirtual>,
1748   _Jv_JNI_CallAnyMethodV<jboolean, nonvirtual>,
1749   _Jv_JNI_CallAnyMethodA<jboolean, nonvirtual>,
1750   _Jv_JNI_CallAnyMethod<jbyte, nonvirtual>,
1751   _Jv_JNI_CallAnyMethodV<jbyte, nonvirtual>,
1752   _Jv_JNI_CallAnyMethodA<jbyte, nonvirtual>,
1753   _Jv_JNI_CallAnyMethod<jchar, nonvirtual>,
1754   _Jv_JNI_CallAnyMethodV<jchar, nonvirtual>,
1755   _Jv_JNI_CallAnyMethodA<jchar, nonvirtual>,
1756   _Jv_JNI_CallAnyMethod<jshort, nonvirtual>,
1757   _Jv_JNI_CallAnyMethodV<jshort, nonvirtual>,
1758   _Jv_JNI_CallAnyMethodA<jshort, nonvirtual>,
1759   _Jv_JNI_CallAnyMethod<jint, nonvirtual>,
1760   _Jv_JNI_CallAnyMethodV<jint, nonvirtual>,
1761   _Jv_JNI_CallAnyMethodA<jint, nonvirtual>,
1762   _Jv_JNI_CallAnyMethod<jlong, nonvirtual>,
1763   _Jv_JNI_CallAnyMethodV<jlong, nonvirtual>,
1764   _Jv_JNI_CallAnyMethodA<jlong, nonvirtual>,
1765   _Jv_JNI_CallAnyMethod<jfloat, nonvirtual>,
1766   _Jv_JNI_CallAnyMethodV<jfloat, nonvirtual>,
1767   _Jv_JNI_CallAnyMethodA<jfloat, nonvirtual>,
1768   _Jv_JNI_CallAnyMethod<jdouble, nonvirtual>,
1769   _Jv_JNI_CallAnyMethodV<jdouble, nonvirtual>,
1770   _Jv_JNI_CallAnyMethodA<jdouble, nonvirtual>,
1771   _Jv_JNI_CallAnyVoidMethod<nonvirtual>,
1772   _Jv_JNI_CallAnyVoidMethodV<nonvirtual>,
1773   _Jv_JNI_CallAnyVoidMethodA<nonvirtual>,
1774
1775   _Jv_JNI_GetAnyFieldID<false>,
1776   _Jv_JNI_GetField<jobject>,
1777   _Jv_JNI_GetField<jboolean>,
1778   _Jv_JNI_GetField<jbyte>,
1779   _Jv_JNI_GetField<jchar>,
1780   _Jv_JNI_GetField<jshort>,
1781   _Jv_JNI_GetField<jint>,
1782   _Jv_JNI_GetField<jlong>,
1783   _Jv_JNI_GetField<jfloat>,
1784   _Jv_JNI_GetField<jdouble>,
1785   _Jv_JNI_SetField,
1786   _Jv_JNI_SetField,
1787   _Jv_JNI_SetField,
1788   _Jv_JNI_SetField,
1789   _Jv_JNI_SetField,
1790   _Jv_JNI_SetField,
1791   _Jv_JNI_SetField,
1792   _Jv_JNI_SetField,
1793   _Jv_JNI_SetField,
1794   _Jv_JNI_GetAnyMethodID<true>,
1795
1796   _Jv_JNI_CallStaticMethod<jobject>,
1797   _Jv_JNI_CallStaticMethodV<jobject>,
1798   _Jv_JNI_CallStaticMethodA<jobject>,
1799   _Jv_JNI_CallStaticMethod<jboolean>,
1800   _Jv_JNI_CallStaticMethodV<jboolean>,
1801   _Jv_JNI_CallStaticMethodA<jboolean>,
1802   _Jv_JNI_CallStaticMethod<jbyte>,
1803   _Jv_JNI_CallStaticMethodV<jbyte>,
1804   _Jv_JNI_CallStaticMethodA<jbyte>,
1805   _Jv_JNI_CallStaticMethod<jchar>,
1806   _Jv_JNI_CallStaticMethodV<jchar>,
1807   _Jv_JNI_CallStaticMethodA<jchar>,
1808   _Jv_JNI_CallStaticMethod<jshort>,
1809   _Jv_JNI_CallStaticMethodV<jshort>,
1810   _Jv_JNI_CallStaticMethodA<jshort>,
1811   _Jv_JNI_CallStaticMethod<jint>,
1812   _Jv_JNI_CallStaticMethodV<jint>,
1813   _Jv_JNI_CallStaticMethodA<jint>,
1814   _Jv_JNI_CallStaticMethod<jlong>,
1815   _Jv_JNI_CallStaticMethodV<jlong>,
1816   _Jv_JNI_CallStaticMethodA<jlong>,
1817   _Jv_JNI_CallStaticMethod<jfloat>,
1818   _Jv_JNI_CallStaticMethodV<jfloat>,
1819   _Jv_JNI_CallStaticMethodA<jfloat>,
1820   _Jv_JNI_CallStaticMethod<jdouble>,
1821   _Jv_JNI_CallStaticMethodV<jdouble>,
1822   _Jv_JNI_CallStaticMethodA<jdouble>,
1823   _Jv_JNI_CallStaticVoidMethod,
1824   _Jv_JNI_CallStaticVoidMethodV,
1825   _Jv_JNI_CallStaticVoidMethodA,
1826
1827   _Jv_JNI_GetAnyFieldID<true>,
1828   _Jv_JNI_GetStaticField<jobject>,
1829   _Jv_JNI_GetStaticField<jboolean>,
1830   _Jv_JNI_GetStaticField<jbyte>,
1831   _Jv_JNI_GetStaticField<jchar>,
1832   _Jv_JNI_GetStaticField<jshort>,
1833   _Jv_JNI_GetStaticField<jint>,
1834   _Jv_JNI_GetStaticField<jlong>,
1835   _Jv_JNI_GetStaticField<jfloat>,
1836   _Jv_JNI_GetStaticField<jdouble>,
1837   _Jv_JNI_SetStaticField,
1838   _Jv_JNI_SetStaticField,
1839   _Jv_JNI_SetStaticField,
1840   _Jv_JNI_SetStaticField,
1841   _Jv_JNI_SetStaticField,
1842   _Jv_JNI_SetStaticField,
1843   _Jv_JNI_SetStaticField,
1844   _Jv_JNI_SetStaticField,
1845   _Jv_JNI_SetStaticField,
1846   _Jv_JNI_NewString,
1847   _Jv_JNI_GetStringLength,
1848   _Jv_JNI_GetStringChars,
1849   _Jv_JNI_ReleaseStringChars,
1850   _Jv_JNI_NewStringUTF,
1851   _Jv_JNI_GetStringUTFLength,
1852   _Jv_JNI_GetStringUTFChars,
1853   _Jv_JNI_ReleaseStringUTFChars,
1854   _Jv_JNI_GetArrayLength,
1855   _Jv_JNI_NewObjectArray,
1856   _Jv_JNI_GetObjectArrayElement,
1857   _Jv_JNI_SetObjectArrayElement,
1858   _Jv_JNI_NewPrimitiveArray<jboolean, JvPrimClass (boolean)>,
1859   _Jv_JNI_NewPrimitiveArray<jbyte, JvPrimClass (byte)>,
1860   _Jv_JNI_NewPrimitiveArray<jchar, JvPrimClass (char)>,
1861   _Jv_JNI_NewPrimitiveArray<jshort, JvPrimClass (short)>,
1862   _Jv_JNI_NewPrimitiveArray<jint, JvPrimClass (int)>,
1863   _Jv_JNI_NewPrimitiveArray<jlong, JvPrimClass (long)>,
1864   _Jv_JNI_NewPrimitiveArray<jfloat, JvPrimClass (float)>,
1865   _Jv_JNI_NewPrimitiveArray<jdouble, JvPrimClass (double)>,
1866   _Jv_JNI_GetPrimitiveArrayElements,
1867   _Jv_JNI_GetPrimitiveArrayElements,
1868   _Jv_JNI_GetPrimitiveArrayElements,
1869   _Jv_JNI_GetPrimitiveArrayElements,
1870   _Jv_JNI_GetPrimitiveArrayElements,
1871   _Jv_JNI_GetPrimitiveArrayElements,
1872   _Jv_JNI_GetPrimitiveArrayElements,
1873   _Jv_JNI_GetPrimitiveArrayElements,
1874   _Jv_JNI_ReleasePrimitiveArrayElements,
1875   _Jv_JNI_ReleasePrimitiveArrayElements,
1876   _Jv_JNI_ReleasePrimitiveArrayElements,
1877   _Jv_JNI_ReleasePrimitiveArrayElements,
1878   _Jv_JNI_ReleasePrimitiveArrayElements,
1879   _Jv_JNI_ReleasePrimitiveArrayElements,
1880   _Jv_JNI_ReleasePrimitiveArrayElements,
1881   _Jv_JNI_ReleasePrimitiveArrayElements,
1882   _Jv_JNI_GetPrimitiveArrayRegion,
1883   _Jv_JNI_GetPrimitiveArrayRegion,
1884   _Jv_JNI_GetPrimitiveArrayRegion,
1885   _Jv_JNI_GetPrimitiveArrayRegion,
1886   _Jv_JNI_GetPrimitiveArrayRegion,
1887   _Jv_JNI_GetPrimitiveArrayRegion,
1888   _Jv_JNI_GetPrimitiveArrayRegion,
1889   _Jv_JNI_GetPrimitiveArrayRegion,
1890   _Jv_JNI_SetPrimitiveArrayRegion,
1891   _Jv_JNI_SetPrimitiveArrayRegion,
1892   _Jv_JNI_SetPrimitiveArrayRegion,
1893   _Jv_JNI_SetPrimitiveArrayRegion,
1894   _Jv_JNI_SetPrimitiveArrayRegion,
1895   _Jv_JNI_SetPrimitiveArrayRegion,
1896   _Jv_JNI_SetPrimitiveArrayRegion,
1897   _Jv_JNI_SetPrimitiveArrayRegion,
1898   NOT_IMPL /* RegisterNatives */,
1899   NOT_IMPL /* UnregisterNatives */,
1900   _Jv_JNI_MonitorEnter,
1901   _Jv_JNI_MonitorExit,
1902   _Jv_JNI_GetJavaVM,
1903
1904   _Jv_JNI_GetStringRegion,
1905   _Jv_JNI_GetStringUTFRegion,
1906   _Jv_JNI_GetPrimitiveArrayCritical,
1907   _Jv_JNI_ReleasePrimitiveArrayCritical,
1908   _Jv_JNI_GetStringCritical,
1909   _Jv_JNI_ReleaseStringCritical,
1910
1911   NOT_IMPL /* newweakglobalref */,
1912   NOT_IMPL /* deleteweakglobalref */,
1913
1914   _Jv_JNI_ExceptionCheck
1915 };
1916
1917 struct JNIInvokeInterface _Jv_JNI_InvokeFunctions =
1918 {
1919   RESERVED,
1920   RESERVED,
1921   RESERVED,
1922
1923   _Jv_JNI_DestroyJavaVM,
1924   _Jv_JNI_AttachCurrentThread,
1925   _Jv_JNI_DetachCurrentThread,
1926   _Jv_JNI_GetEnv
1927 };