OSDN Git Service

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