* native_resolve_function: implemented -verbose:jni
[cacao.git] / src / native / native.c
1 /* src/native/native.c - table of native functions
2
3    Copyright (C) 1996-2005 R. Grafl, A. Krall, C. Kruegel, C. Oates,
4    R. Obermaisser, M. Platter, M. Probst, S. Ring, E. Steiner,
5    C. Thalinger, D. Thuernbeck, P. Tomsich, C. Ullrich, J. Wenninger,
6    Institut f. Computersprachen - TU Wien
7
8    This file is part of CACAO.
9
10    This program is free software; you can redistribute it and/or
11    modify it under the terms of the GNU General Public License as
12    published by the Free Software Foundation; either version 2, or (at
13    your option) any later version.
14
15    This program is distributed in the hope that it will be useful, but
16    WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18    General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with this program; if not, write to the Free Software
22    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
23    02111-1307, USA.
24
25    Contact: cacao@complang.tuwien.ac.at
26
27    Authors: Reinhard Grafl
28             Roman Obermaisser
29             Andreas Krall
30
31    Changes: Christian Thalinger
32
33    $Id: native.c 2891 2005-07-04 20:31:45Z twisti $
34
35 */
36
37
38 #include <assert.h>
39
40 #if !defined(ENABLE_STATICVM)
41 # include "libltdl/ltdl.h"
42 #endif
43
44 #include "config.h"
45 #include "types.h"
46 #include "cacao/cacao.h"
47 #include "mm/memory.h"
48 #include "native/jni.h"
49 #include "native/native.h"
50 #include "native/include/java_lang_Throwable.h"
51 #include "toolbox/logging.h"
52 #include "vm/builtin.h"
53 #include "vm/exceptions.h"
54 #include "vm/global.h"
55 #include "vm/loader.h"
56 #include "vm/options.h"
57 #include "vm/resolve.h"
58 #include "vm/stringlocal.h"
59 #include "vm/tables.h"
60 #include "vm/jit/asmpart.h"
61 #include "vm/jit/jit.h"
62
63
64 /* include table of native functions ******************************************/
65
66 #include "native/include/java_lang_Cloneable.h"
67 #include "native/include/java_util_Properties.h"
68 #include "native/include/java_io_InputStream.h"
69 #include "native/include/java_io_PrintStream.h"
70
71 #include "native/include/gnu_classpath_VMStackWalker.h"
72 #include "native/include/gnu_classpath_VMSystemProperties.h"
73 #include "native/include/java_lang_Class.h"
74 #include "native/include/java_lang_Object.h"
75 #include "native/include/java_lang_VMClass.h"
76 #include "native/include/java_lang_VMClassLoader.h"
77 #include "native/include/java_lang_VMObject.h"
78 #include "native/include/java_lang_VMRuntime.h"
79 #include "native/include/java_lang_VMString.h"
80 #include "native/include/java_lang_VMSystem.h"
81 #include "native/include/java_lang_VMThread.h"
82 #include "native/include/java_lang_VMThrowable.h"
83 #include "native/include/java_lang_reflect_Constructor.h"
84 #include "native/include/java_lang_reflect_Field.h"
85 #include "native/include/java_lang_reflect_Proxy.h"
86 #include "native/include/java_lang_reflect_Method.h"
87 #include "native/include/java_security_VMAccessController.h"
88
89 #if defined(ENABLE_STATICVM)
90
91 /* these are required to prevent compiler warnings */
92
93 #include "native/include/java_net_DatagramPacket.h"
94 #include "native/include/java_net_InetAddress.h"
95 #include "native/include/java_net_SocketImpl.h"
96
97 #include "native/include/gnu_java_net_PlainDatagramSocketImpl.h"
98 #include "native/include/gnu_java_net_PlainSocketImpl.h"
99 #include "native/include/gnu_java_nio_PipeImpl.h"
100 #include "native/include/gnu_java_nio_channels_FileChannelImpl.h"
101 #include "native/include/gnu_java_nio_charset_iconv_IconvEncoder.h"
102 #include "native/include/gnu_java_nio_charset_iconv_IconvDecoder.h"
103 #include "native/include/java_lang_VMProcess.h"
104 #include "native/include/java_nio_MappedByteBufferImpl.h"
105 #include "native/include/java_nio_channels_spi_SelectorProvider.h"
106
107 /* now include the native table */
108
109 #include "native/nativetable.inc"
110
111 #else /* defined(ENABLE_STATICVM) */
112
113 /* Ensure that symbols for functions implemented within CACAO are used and    */
114 /* exported to dlopen.                                                        */
115
116 static functionptr dummynativetable[] = {
117         (functionptr) Java_gnu_classpath_VMStackWalker_getClassContext,
118
119         (functionptr) Java_gnu_classpath_VMSystemProperties_preInit,
120
121         (functionptr) Java_java_lang_VMClass_isInstance,
122         (functionptr) Java_java_lang_VMClass_isAssignableFrom,
123         (functionptr) Java_java_lang_VMClass_isInterface,
124         (functionptr) Java_java_lang_VMClass_isPrimitive,
125         (functionptr) Java_java_lang_VMClass_getName,
126         (functionptr) Java_java_lang_VMClass_getSuperclass,
127         (functionptr) Java_java_lang_VMClass_getInterfaces,
128         (functionptr) Java_java_lang_VMClass_getComponentType,
129         (functionptr) Java_java_lang_VMClass_getModifiers,
130         (functionptr) Java_java_lang_VMClass_getDeclaringClass,
131         (functionptr) Java_java_lang_VMClass_getDeclaredClasses,
132         (functionptr) Java_java_lang_VMClass_getDeclaredFields,
133         (functionptr) Java_java_lang_VMClass_getDeclaredMethods,
134         (functionptr) Java_java_lang_VMClass_getDeclaredConstructors,
135         (functionptr) Java_java_lang_VMClass_getClassLoader,
136         (functionptr) Java_java_lang_VMClass_forName,
137         (functionptr) Java_java_lang_VMClass_isArray,
138         (functionptr) Java_java_lang_VMClass_initialize,
139         (functionptr) Java_java_lang_VMClass_loadArrayClass,
140         (functionptr) Java_java_lang_VMClass_throwException,
141
142         (functionptr) Java_java_lang_VMClassLoader_defineClass,
143         (functionptr) Java_java_lang_VMClassLoader_resolveClass,
144         (functionptr) Java_java_lang_VMClassLoader_loadClass,
145         (functionptr) Java_java_lang_VMClassLoader_getPrimitiveClass,
146         (functionptr) Java_java_lang_VMClassLoader_nativeGetResources,
147
148         (functionptr) Java_java_lang_VMObject_getClass,
149         (functionptr) Java_java_lang_VMObject_clone,
150         (functionptr) Java_java_lang_VMObject_notify,
151         (functionptr) Java_java_lang_VMObject_notifyAll,
152         (functionptr) Java_java_lang_VMObject_wait,
153
154         (functionptr) Java_java_lang_VMRuntime_availableProcessors,
155         (functionptr) Java_java_lang_VMRuntime_freeMemory,
156         (functionptr) Java_java_lang_VMRuntime_totalMemory,
157         (functionptr) Java_java_lang_VMRuntime_maxMemory,
158         (functionptr) Java_java_lang_VMRuntime_gc,
159         (functionptr) Java_java_lang_VMRuntime_runFinalization,
160         (functionptr) Java_java_lang_VMRuntime_runFinalizationForExit,
161         (functionptr) Java_java_lang_VMRuntime_traceInstructions,
162         (functionptr) Java_java_lang_VMRuntime_traceMethodCalls,
163         (functionptr) Java_java_lang_VMRuntime_runFinalizersOnExit,
164         (functionptr) Java_java_lang_VMRuntime_exit,
165         (functionptr) Java_java_lang_VMRuntime_nativeLoad,
166         (functionptr) Java_java_lang_VMRuntime_mapLibraryName,
167
168         (functionptr) Java_java_lang_VMString_intern,
169
170         (functionptr) Java_java_lang_VMSystem_arraycopy,
171         (functionptr) Java_java_lang_VMSystem_identityHashCode,
172
173         (functionptr) Java_java_lang_VMThread_start,
174         (functionptr) Java_java_lang_VMThread_interrupt,
175         (functionptr) Java_java_lang_VMThread_isInterrupted,
176         (functionptr) Java_java_lang_VMThread_suspend,
177         (functionptr) Java_java_lang_VMThread_resume,
178         (functionptr) Java_java_lang_VMThread_nativeSetPriority,
179         (functionptr) Java_java_lang_VMThread_nativeStop,
180         (functionptr) Java_java_lang_VMThread_currentThread,
181         (functionptr) Java_java_lang_VMThread_yield,
182         (functionptr) Java_java_lang_VMThread_interrupted,
183         (functionptr) Java_java_lang_VMThread_holdsLock,
184
185         (functionptr) Java_java_lang_VMThrowable_fillInStackTrace,
186         (functionptr) Java_java_lang_VMThrowable_getStackTrace,
187
188         (functionptr) Java_java_lang_reflect_Constructor_getModifiers,
189         (functionptr) Java_java_lang_reflect_Constructor_constructNative,
190
191         (functionptr) Java_java_lang_reflect_Field_getModifiers,
192         (functionptr) Java_java_lang_reflect_Field_getType,
193         (functionptr) Java_java_lang_reflect_Field_get,
194         (functionptr) Java_java_lang_reflect_Field_getBoolean,
195         (functionptr) Java_java_lang_reflect_Field_getByte,
196         (functionptr) Java_java_lang_reflect_Field_getChar,
197         (functionptr) Java_java_lang_reflect_Field_getShort,
198         (functionptr) Java_java_lang_reflect_Field_getInt,
199         (functionptr) Java_java_lang_reflect_Field_getLong,
200         (functionptr) Java_java_lang_reflect_Field_getFloat,
201         (functionptr) Java_java_lang_reflect_Field_getDouble,
202         (functionptr) Java_java_lang_reflect_Field_set,
203         (functionptr) Java_java_lang_reflect_Field_setBoolean,
204         (functionptr) Java_java_lang_reflect_Field_setByte,
205         (functionptr) Java_java_lang_reflect_Field_setChar,
206         (functionptr) Java_java_lang_reflect_Field_setShort,
207         (functionptr) Java_java_lang_reflect_Field_setInt,
208         (functionptr) Java_java_lang_reflect_Field_setLong,
209         (functionptr) Java_java_lang_reflect_Field_setFloat,
210         (functionptr) Java_java_lang_reflect_Field_setDouble,
211
212         (functionptr) Java_java_lang_reflect_Proxy_getProxyClass0,
213         (functionptr) Java_java_lang_reflect_Proxy_getProxyData0,
214         (functionptr) Java_java_lang_reflect_Proxy_generateProxyClass0,
215
216         (functionptr) Java_java_lang_reflect_Method_getModifiers,
217         (functionptr) Java_java_lang_reflect_Method_getReturnType,
218         (functionptr) Java_java_lang_reflect_Method_getParameterTypes,
219         (functionptr) Java_java_lang_reflect_Method_getExceptionTypes,
220         (functionptr) Java_java_lang_reflect_Method_invokeNative,
221
222         (functionptr) Java_java_security_VMAccessController_getStack,
223 };
224
225 #endif /* defined(ENABLE_STATICVM) */
226
227
228 /************* use classinfo structure as java.lang.Class object **************/
229
230 bool use_class_as_object(classinfo *c)
231 {
232         if (!c->classvftbl) {
233                 /* is the class loaded */
234                 if (!c->loaded) {
235 /*                      if (!class_load(c)) */
236 /*                              throw_exception_exit(); */
237                         log_text("use_class_as_object: class_load should not happen");
238                         assert(0);
239                 }
240
241                 /* is the class linked */
242                 if (!c->linked)
243                         if (!link_class(c))
244                                 return false;
245
246                 assert(class_java_lang_Class);
247
248                 c->header.vftbl = class_java_lang_Class->vftbl;
249                 c->classvftbl = true;
250         }
251
252         return true;
253 }
254
255
256 /************************** tables for methods ********************************/
257
258 #undef JOWENN_DEBUG
259 #undef JOWENN_DEBUG1
260
261 #ifdef ENABLE_STATICVM
262 #define NATIVETABLESIZE  (sizeof(nativetable)/sizeof(struct nativeref))
263
264 /* table for fast string comparison */
265 static nativecompref nativecomptable[NATIVETABLESIZE];
266
267 /* string comparsion table initialized */
268 static bool nativecompdone = false;
269 #endif
270
271
272 /* XXX don't define this in a header file!!! */
273
274 static struct nativeCall nativeCalls[] =
275 {
276 #include "nativecalls.inc"
277 };
278
279 #define NATIVECALLSSIZE    (sizeof(nativeCalls) / sizeof(struct nativeCall))
280
281 struct nativeCompCall nativeCompCalls[NATIVECALLSSIZE];
282
283
284 /* global variables ***********************************************************/
285
286 #if !defined(ENABLE_STATICVM)
287 static hashtable library_hash;
288 static lt_dlhandle mainhandle;
289 #endif
290
291
292 /* native_loadclasses **********************************************************
293
294    Load classes required for native methods.
295
296 *******************************************************************************/
297
298 bool native_init(void)
299 {
300 #if !defined(ENABLE_STATICVM)
301         void *p;
302
303         /* We need to access the dummy native table, not only to remove a warning */
304         /* but to be sure that the table is not optimized away (gcc does this     */
305         /* since 3.4).                                                            */
306
307         p = &dummynativetable;
308
309         /* initialize libltdl */
310
311         if (lt_dlinit()) {
312                 /* XXX how can we throw an exception here? */
313                 log_text(lt_dlerror());
314
315                 return false;
316         }
317
318         /* get the handle for the main program */
319
320         if (!(mainhandle = lt_dlopen(NULL)))
321                 return false;
322
323         /* initialize library hashtable, 10 entries should be enough */
324
325         init_hashtable(&library_hash, 10);
326
327 #endif
328
329         /* everything's ok */
330
331         return true;
332 }
333
334
335 /* native_library_hash_add *****************************************************
336
337    Adds an entry to the native library hashtable.
338
339 *******************************************************************************/
340
341 #if !defined(ENABLE_STATICVM)
342 void native_library_hash_add(utf *filename, java_objectheader *loader,
343                                                          lt_dlhandle handle)
344 {
345         library_hash_loader_entry *le;
346         library_hash_name_entry   *ne;      /* library name                       */
347         u4   key;                           /* hashkey                            */
348         u4   slot;                          /* slot in hashtable                  */
349
350         /* normally addresses are aligned to 4, 8 or 16 bytes */
351
352         key = ((u4) (ptrint) loader) >> 4;         /* align to 16-byte boundaries */
353         slot = key & (library_hash.size - 1);
354         le = library_hash.ptr[slot];
355
356         /* search external hash chain for the entry */
357
358         while (le) {
359                 if (le->loader == loader)
360                         break;
361
362                 le = le->hashlink;                  /* next element in external chain */
363         }
364
365         /* no loader found? create a new entry */
366
367         if (!le) {
368                 le = NEW(library_hash_loader_entry);
369
370                 le->loader = loader;
371                 le->namelink = NULL;
372
373                 /* insert entry into hashtable */
374
375                 le->hashlink = (library_hash_loader_entry *) library_hash.ptr[slot];
376                 library_hash.ptr[slot] = le;
377
378                 /* update number of hashtable-entries */
379
380                 library_hash.entries++;
381         }
382
383
384         /* search for library name */
385
386         ne = le->namelink;
387
388         while (ne) {
389                 if (ne->name == filename)
390                         return;
391
392                 ne = ne->hashlink;                  /* next element in external chain */
393         }
394
395         /* not found? add the library name to the classloader */
396
397         ne = NEW(library_hash_name_entry);
398
399         ne->name = filename;
400         ne->handle = handle;
401
402         /* insert entry into external chain */
403
404         ne->hashlink = le->namelink;
405         le->namelink = ne;
406 }
407 #endif /* !defined(ENABLE_STATICVM) */
408
409
410 /* native_findfunction *********************************************************
411
412    Looks up a method (must have the same class name, method name,
413    descriptor and 'static'ness) and returns a function pointer to it.
414    Returns: function pointer or NULL (if there is no such method)
415
416    Remark: For faster operation, the names/descriptors are converted
417    from C strings to Unicode the first time this function is called.
418
419 *******************************************************************************/
420
421 #if defined(ENABLE_STATICVM)
422 functionptr native_findfunction(utf *cname, utf *mname, utf *desc,
423                                                                 bool isstatic)
424 {
425         /* entry of table for fast string comparison */
426         struct nativecompref *n;
427         s4 i;
428
429         isstatic = isstatic ? true : false;
430         
431         if (!nativecompdone) {
432                 for (i = 0; i < NATIVETABLESIZE; i++) {
433                         nativecomptable[i].classname  = 
434                                 utf_new_char(nativetable[i].classname);
435
436                         nativecomptable[i].methodname = 
437                                 utf_new_char(nativetable[i].methodname);
438
439                         nativecomptable[i].descriptor =
440                                 utf_new_char(nativetable[i].descriptor);
441
442                         nativecomptable[i].isstatic   = nativetable[i].isstatic;
443                         nativecomptable[i].func       = nativetable[i].func;
444                 }
445
446                 nativecompdone = true;
447         }
448
449         for (i = 0; i < NATIVETABLESIZE; i++) {
450                 n = &(nativecomptable[i]);
451
452                 if (cname == n->classname && mname == n->methodname &&
453                     desc == n->descriptor && isstatic == n->isstatic)
454                         return n->func;
455         }
456
457                 
458         /* no function was found, throw exception */
459
460         *exceptionptr =
461                         new_exception_utfmessage(string_java_lang_UnsatisfiedLinkError,
462                                                                          mname);
463
464         return NULL;
465 }
466 #endif /* defined(ENABLE_STATICVM) */
467
468
469 /* native_make_overloaded_function *********************************************
470
471    XXX
472
473 *******************************************************************************/
474
475 #if !defined(ENABLE_STATICVM)
476 static char *native_make_overloaded_function(char *name, utf *desc)
477 {
478         char *newname;
479         s4    namelen;
480         char *utf_ptr;
481         u2    c;
482         s4    i;
483
484         utf_ptr = desc->text;
485         namelen = strlen(name) + strlen("__") + strlen("0");
486
487         /* calculate additional length */
488
489         while ((c = utf_nextu2(&utf_ptr)) != ')') {
490                 switch (c) {
491                 case 'Z':
492                 case 'B':
493                 case 'C':
494                 case 'S':
495                 case 'I':
496                 case 'J':
497                 case 'F':
498                 case 'D':
499                         namelen++;
500                         break;
501                 case '[':
502                         namelen += 2;
503                         break;
504                 case 'L':
505                         namelen++;
506                         while (utf_nextu2(&utf_ptr) != ';')
507                                 namelen++;
508                         namelen += 2;
509                         break;
510                 case '(':
511                         break;
512                 default:
513                         assert(0);
514                 }
515         }
516
517
518         /* reallocate memory */
519
520         i = strlen(name);
521
522         newname = DMNEW(char, namelen);
523         MCOPY(newname, name, char, i);
524
525         utf_ptr = desc->text;
526
527         newname[i++] = '_';
528         newname[i++] = '_';
529
530         while ((c = utf_nextu2(&utf_ptr)) != ')') {
531                 switch (c) {
532                 case 'Z':
533                 case 'B':
534                 case 'C':
535                 case 'S':
536                 case 'J':
537                 case 'I':
538                 case 'F':
539                 case 'D':
540                         newname[i++] = c;
541                         break;
542                 case '[':
543                         newname[i++] = '_';
544                         newname[i++] = '3';
545                         break;
546                 case 'L':
547                         newname[i++] = 'L';
548                         while ((c = utf_nextu2(&utf_ptr)) != ';')
549                                 if (((c >= 'a') && (c <= 'z')) ||
550                                         ((c >= 'A') && (c <= 'Z')) ||
551                                         ((c >= '0') && (c <= '9')))
552                                         newname[i++] = c;
553                                 else
554                                         newname[i++] = '_';
555                         newname[i++] = '_';
556                         newname[i++] = '2';
557                         break;
558                 case '(':
559                         break;
560                 default:
561                         assert(0);
562                 }
563         }
564
565         /* close string */
566
567         newname[i] = '\0';
568
569         return newname;
570 }
571
572
573 /* native_resolve_function *****************************************************
574
575    Resolves a native function, maybe from a dynamic library.
576
577 *******************************************************************************/
578
579 functionptr native_resolve_function(methodinfo *m)
580 {
581         lt_ptr                     sym;
582         char                      *name;
583         char                      *newname;
584         s4                         namelen;
585         char                      *utf_ptr;
586         char                      *utf_endptr;
587         s4                         dumpsize;
588         library_hash_loader_entry *le;
589         library_hash_name_entry   *ne;
590         u4                         key;     /* hashkey                            */
591         u4                         slot;    /* slot in hashtable                  */
592         u4                         i;
593
594
595         /* verbose output */
596
597         if (opt_verbosejni) {
598                 printf("[Dynamic-linking native method ");
599                 utf_display_classname(m->class->name);
600                 printf(".");
601                 utf_display(m->name);
602                 printf(" ... ");
603         }
604                 
605         /* calculate length of native function name */
606
607         namelen = strlen("Java_") + utf_strlen(m->class->name) + strlen("_") +
608                 utf_strlen(m->name) + strlen("0");
609
610         /* check for underscores in class name */
611
612         utf_ptr = m->class->name->text;
613         utf_endptr = UTF_END(m->class->name);
614
615         while (utf_ptr < utf_endptr)
616                 if (utf_nextu2(&utf_ptr) == '_')
617                         namelen++;
618
619         /* check for underscores in method name */
620
621         utf_ptr = m->name->text;
622         utf_endptr = UTF_END(m->name);
623
624         while (utf_ptr < utf_endptr)
625                 if (utf_nextu2(&utf_ptr) == '_')
626                         namelen++;
627
628         /* allocate memory */
629
630         dumpsize = dump_size();
631
632         name = DMNEW(char, namelen);
633
634
635         /* generate name of native functions */
636
637         strcpy(name, "Java_");
638         i = strlen("Java_");
639
640         utf_ptr = m->class->name->text;
641         utf_endptr = UTF_END(m->class->name);
642
643         for (; utf_ptr < utf_endptr; utf_ptr++, i++) {
644                 name[i] = *utf_ptr;
645
646                 /* escape sequence for '_' is '_1' */
647
648                 if (name[i] == '_')
649                         name[++i] = '1';
650
651                 /* replace '/' with '_' */
652
653                 if (name[i] == '/')
654                         name[i] = '_';
655         }
656
657         /* seperator between class and method */
658
659         name[i++] = '_';
660
661         utf_ptr = m->name->text;
662         utf_endptr = UTF_END(m->name);
663
664         for (; utf_ptr < utf_endptr; utf_ptr++, i++) {
665                 name[i] = *utf_ptr;
666
667                 /* escape sequence for '_' is '_1' */
668
669                 if (name[i] == '_')
670                         name[++i] = '1';
671         }
672
673         /* close string */
674
675         name[i] = '\0';
676
677
678         /* check the library hash entries of the classloader of the methods's     */
679         /* class                                                                  */
680
681         sym = NULL;
682
683         /* normally addresses are aligned to 4, 8 or 16 bytes */
684
685         key = ((u4) (ptrint) m->class->classloader) >> 4; /* align to 16-byte */
686         slot = key & (library_hash.size - 1);
687         le = library_hash.ptr[slot];
688
689         /* iterate through loaders in this hash slot */
690
691         while (le && !sym) {
692                 /* iterate through names in this loader */
693
694                 ne = le->namelink;
695                         
696                 while (ne && !sym) {
697                         sym = lt_dlsym(ne->handle, name);
698
699                         if (!sym)
700                                 sym = lt_dlsym(ne->handle, newname);
701
702                         ne = ne->hashlink;
703                 }
704
705                 le = le->hashlink;
706         }
707
708         if (sym)
709                 if (opt_verbosejni)
710                         printf("JNI ]\n");
711
712
713         /* if not found, try to find the native function symbol in the main       */
714         /* program                                                                */
715
716         if (!sym) {
717                 sym = lt_dlsym(mainhandle, name);
718
719                 if (!sym) {
720                         /* we didn't find the symbol yet, try to resolve an overloaded    */
721                         /* function (having the types in it's name)                       */
722
723                         newname = native_make_overloaded_function(name, m->descriptor);
724
725                         /* try to find the overloaded symbol */
726
727                         sym = lt_dlsym(mainhandle, newname);
728                 }
729
730                 if (sym)
731                         if (opt_verbosejni)
732                                 printf("internal ]\n");
733         }
734
735
736         /* no symbol found? throw exception */
737
738         if (!sym)
739                 *exceptionptr =
740                         new_exception_utfmessage(string_java_lang_UnsatisfiedLinkError,
741                                                                          m->name);
742
743         /* release memory */
744
745         dump_release(dumpsize);
746
747         return (functionptr) (ptrint) sym;
748 }
749 #endif /* !defined(ENABLE_STATICVM) */
750
751
752 /****************** function class_findfield_approx ****************************
753         
754         searches in 'classinfo'-structure for a field with the
755         specified name
756
757 *******************************************************************************/
758  
759 fieldinfo *class_findfield_approx(classinfo *c, utf *name)
760 {
761         s4 i;
762
763         for (i = 0; i < c->fieldscount; i++) {
764                 /* compare field names */
765                 if ((c->fields[i].name == name))
766                         return &(c->fields[i]);
767         }
768
769         /* field was not found, raise exception */      
770         *exceptionptr = new_exception(string_java_lang_NoSuchFieldException);
771
772         return NULL;
773 }
774
775
776 s4 class_findfield_index_approx(classinfo *c, utf *name)
777 {
778         s4 i;
779
780         for (i = 0; i < c->fieldscount; i++) {
781                 /* compare field names */
782                 if ((c->fields[i].name == name))
783                         return i;
784         }
785
786         /* field was not found, raise exception */      
787         *exceptionptr = new_exception(string_java_lang_NoSuchFieldException);
788
789         return -1;
790 }
791
792
793 /* native_new_and_init *********************************************************
794
795    Creates a new object on the heap and calls the initializer.
796    Returns the object pointer or NULL if memory is exhausted.
797                         
798 *******************************************************************************/
799
800 java_objectheader *native_new_and_init(classinfo *c)
801 {
802         methodinfo *m;
803         java_objectheader *o;
804
805         if (!c)
806                 return *exceptionptr;
807
808         /* create object */
809
810         o = builtin_new(c);
811         
812         if (!o)
813                 return NULL;
814
815         /* find initializer */
816
817         m = class_findmethod(c, utf_init, utf_void__void);
818                                                       
819         /* initializer not found */
820
821         if (!m)
822                 return o;
823
824         /* call initializer */
825
826         asm_calljavafunction(m, o, NULL, NULL, NULL);
827
828         return o;
829 }
830
831
832 java_objectheader *native_new_and_init_string(classinfo *c, java_lang_String *s)
833 {
834         methodinfo *m;
835         java_objectheader *o;
836
837         if (!c)
838                 return *exceptionptr;
839
840         /* create object */
841
842         o = builtin_new(c);
843
844         if (!o)
845                 return NULL;
846
847         /* find initializer */
848
849         m = class_resolveclassmethod(c,
850                                                                  utf_init,
851                                                                  utf_java_lang_String__void,
852                                                                  NULL,
853                                                                  true);
854
855         /* initializer not found */
856
857         if (!m)
858                 return NULL;
859
860         /* call initializer */
861
862         asm_calljavafunction(m, o, s, NULL, NULL);
863
864         return o;
865 }
866
867
868 java_objectheader *native_new_and_init_int(classinfo *c, s4 i)
869 {
870         methodinfo *m;
871         java_objectheader *o;
872
873         if (!c)
874                 return *exceptionptr;
875
876         /* create object */
877
878         o = builtin_new(c);
879         
880         if (!o)
881                 return NULL;
882
883         /* find initializer */
884
885         m = class_resolveclassmethod(c, utf_init, utf_int__void, NULL, true);
886
887         /* initializer not found  */
888
889         if (!m)
890                 return NULL;
891
892         /* call initializer */
893
894         asm_calljavafunction(m, o, (void *) (ptrint) i, NULL, NULL);
895
896         return o;
897 }
898
899
900 java_objectheader *native_new_and_init_throwable(classinfo *c, java_lang_Throwable *t)
901 {
902         methodinfo *m;
903         java_objectheader *o;
904
905         if (!c)
906                 return *exceptionptr;
907
908         /* create object */
909
910         o = builtin_new(c);
911         
912         if (!o)
913                 return NULL;
914
915         /* find initializer */
916
917         m = class_findmethod(c, utf_init, utf_java_lang_Throwable__void);
918                                                       
919         /* initializer not found */
920
921         if (!m)
922                 return NULL;
923
924         /* call initializer */
925
926         asm_calljavafunction(m, o, t, NULL, NULL);
927
928         return o;
929 }
930
931
932 void copy_vftbl(vftbl_t **dest, vftbl_t *src)
933 {
934     *dest = src;
935 #if 0
936     /* XXX this kind of copying does not work (in the general
937      * case). The interface tables would have to be copied, too. I
938      * don't see why we should make a copy anyway. -Edwin
939      */
940         *dest = mem_alloc(sizeof(vftbl) + sizeof(methodptr)*(src->vftbllength-1));
941         memcpy(*dest, src, sizeof(vftbl) - sizeof(methodptr));
942         memcpy(&(*dest)->table, &src->table, src->vftbllength * sizeof(methodptr));
943 #endif
944 }
945
946
947 /******************************************************************************************                                                                                                             
948
949         creates method signature (excluding return type) from array of 
950         class-objects representing the parameters of the method 
951
952 *******************************************************************************************/
953
954
955 utf *create_methodsig(java_objectarray* types, char *retType)
956 {
957     char *buffer;       /* buffer for building the desciptor */
958     char *pos;          /* current position in buffer */
959     utf *result;        /* the method signature */
960     u4 buffer_size = 3; /* minimal size=3: room for parenthesis and returntype */
961     u4 i, j;
962  
963     if (!types) return NULL;
964
965     /* determine required buffer-size */    
966     for (i = 0; i < types->header.size; i++) {
967                 classinfo *c = (classinfo *) types->data[i];
968                 buffer_size  = buffer_size + c->name->blength + 2;
969     }
970
971     if (retType) buffer_size += strlen(retType);
972
973     /* allocate buffer */
974     buffer = MNEW(char, buffer_size);
975     pos    = buffer;
976     
977     /* method-desciptor starts with parenthesis */
978     *pos++ = '(';
979
980     for (i = 0; i < types->header.size; i++) {
981                 char ch;           
982
983                 /* current argument */
984             classinfo *c = (classinfo *) types->data[i];
985
986             /* current position in utf-text */
987             char *utf_ptr = c->name->text; 
988             
989             /* determine type of argument */
990             if ((ch = utf_nextu2(&utf_ptr)) == '[') {
991                 /* arrayclass */
992                 for (utf_ptr--; utf_ptr < UTF_END(c->name); utf_ptr++) {
993                                 *pos++ = *utf_ptr; /* copy text */
994                         }
995
996             } else {            
997                         /* check for primitive types */
998                         for (j = 0; j < PRIMITIVETYPE_COUNT; j++) {
999                                 char *utf_pos   = utf_ptr - 1;
1000                                 char *primitive = primitivetype_table[j].wrapname;
1001
1002                                 /* compare text */
1003                                 while (utf_pos < UTF_END(c->name)) {
1004                                         if (*utf_pos++ != *primitive++) goto nomatch;
1005                                 }
1006
1007                                 /* primitive type found */
1008                                 *pos++ = primitivetype_table[j].typesig;
1009                                 goto next_type;
1010
1011                         nomatch:
1012                                 ;
1013                         }
1014
1015                         /* no primitive type and no arrayclass, so must be object */
1016                         *pos++ = 'L';
1017
1018                         /* copy text */
1019                         for (utf_ptr--; utf_ptr < UTF_END(c->name); utf_ptr++) {
1020                                 *pos++ = *utf_ptr;
1021                         }
1022
1023                         *pos++ = ';';
1024
1025                 next_type:
1026                         ;
1027                 }  
1028     }       
1029
1030     *pos++ = ')';
1031
1032     if (retType) {
1033                 for (i = 0; i < strlen(retType); i++) {
1034                         *pos++ = retType[i];
1035                 }
1036     }
1037
1038     /* create utf-string */
1039     result = utf_new(buffer, (pos - buffer));
1040     MFREE(buffer, char, buffer_size);
1041
1042     return result;
1043 }
1044
1045
1046 /* native_get_parametertypes ***************************************************
1047
1048    Use the descriptor of a method to generate a java/lang/Class array
1049    which contains the classes of the parametertypes of the method.
1050
1051 *******************************************************************************/
1052
1053 java_objectarray *native_get_parametertypes(methodinfo *m)
1054 {
1055         methoddesc       *md;
1056         typedesc         *paramtypes;
1057         s4                paramcount;
1058     java_objectarray *oa;
1059         s4                i;
1060
1061         md = m->parseddesc;
1062
1063         /* is the descriptor fully parsed? */
1064
1065         if (!m->parseddesc->params)
1066                 if (!descriptor_params_from_paramtypes(md, m->flags))
1067                         return NULL;
1068
1069         paramtypes = md->paramtypes;
1070         paramcount = md->paramcount;
1071
1072         /* skip `this' pointer */
1073
1074         if (!(m->flags & ACC_STATIC)) {
1075                 paramtypes++;
1076                 paramcount--;
1077         }
1078
1079         /* create class-array */
1080
1081         oa = builtin_anewarray(paramcount, class_java_lang_Class);
1082
1083         if (!oa)
1084                 return NULL;
1085
1086     /* get classes */
1087
1088         for (i = 0; i < paramcount; i++) {
1089                 if (!resolve_class_from_typedesc(&paramtypes[i], true, false,
1090                                                                                  (classinfo **) &oa->data[i]))
1091                         return NULL;
1092
1093                 use_class_as_object((classinfo *) oa->data[i]);
1094         }
1095
1096         return oa;
1097 }
1098
1099
1100 /* native_get_exceptiontypes ***************************************************
1101
1102    Get the exceptions which can be thrown by a method.
1103
1104 *******************************************************************************/
1105
1106 java_objectarray *native_get_exceptiontypes(methodinfo *m)
1107 {
1108     u2                excount;
1109     java_objectarray *oa;
1110         classinfo        *c;
1111     u2                i;
1112
1113         /* create class-array */
1114
1115     oa = builtin_anewarray(excount, class_java_lang_Class);
1116
1117         if (!oa)
1118                 return NULL;
1119
1120         /* get exceptions */
1121
1122         excount = m->thrownexceptionscount;
1123
1124     for (i = 0; i < excount; i++) {
1125                 if (!resolve_classref_or_classinfo(NULL, m->thrownexceptions[i],
1126                                                                                    resolveEager, true, false, &c))
1127                         return NULL;
1128
1129                 use_class_as_object(c);
1130
1131                 oa->data[i] = (java_objectheader *) c;
1132     }
1133
1134     return oa;
1135 }
1136
1137
1138 /* native_get_returntype *******************************************************
1139
1140    Get the returntype class of a method.
1141
1142 *******************************************************************************/
1143
1144 classinfo *native_get_returntype(methodinfo *m)
1145 {
1146         classinfo *c;
1147
1148         if (!resolve_class_from_typedesc(&(m->parseddesc->returntype), true, false,
1149                                                                          &c))
1150                 return NULL;
1151
1152         use_class_as_object(c);
1153
1154         return c;
1155 }
1156
1157
1158 /*****************************************************************************/
1159 /*****************************************************************************/
1160
1161
1162 /*--------------------------------------------------------*/
1163 void printNativeCall(nativeCall nc) {
1164   int i,j;
1165
1166   printf("\n%s's Native Methods call:\n",nc.classname); fflush(stdout);
1167   for (i=0; i<nc.methCnt; i++) {  
1168       printf("\tMethod=%s %s\n",nc.methods[i].methodname, nc.methods[i].descriptor);fflush(stdout);
1169
1170     for (j=0; j<nc.callCnt[i]; j++) {  
1171         printf("\t\t<%i,%i>aCalled = %s %s %s\n",i,j,
1172         nc.methods[i].methodCalls[j].classname, 
1173         nc.methods[i].methodCalls[j].methodname, 
1174         nc.methods[i].methodCalls[j].descriptor);fflush(stdout);
1175       }
1176     }
1177   printf("-+++++--------------------\n");fflush(stdout);
1178 }
1179
1180 /*--------------------------------------------------------*/
1181 void printCompNativeCall(nativeCompCall nc) {
1182   int i,j;
1183   printf("printCompNativeCall BEGIN\n");fflush(stdout); 
1184   printf("\n%s's Native Comp Methods call:\n",nc.classname->text);fflush(stdout);
1185   utf_display(nc.classname); fflush(stdout);
1186   
1187   for (i=0; i<nc.methCnt; i++) {  
1188     printf("\tMethod=%s %s\n",nc.methods[i].methodname->text,nc.methods[i].descriptor->text);fflush(stdout);
1189     utf_display(nc.methods[i].methodname); fflush(stdout);
1190     utf_display(nc.methods[i].descriptor);fflush(stdout);
1191     printf("\n");fflush(stdout);
1192
1193     for (j=0; j<nc.callCnt[i]; j++) {  
1194       printf("\t\t<%i,%i>bCalled = ",i,j);fflush(stdout);
1195         utf_display(nc.methods[i].methodCalls[j].classname);fflush(stdout);
1196         utf_display(nc.methods[i].methodCalls[j].methodname); fflush(stdout);
1197         utf_display(nc.methods[i].methodCalls[j].descriptor);fflush(stdout);
1198         printf("\n");fflush(stdout);
1199       }
1200     }
1201 printf("---------------------\n");fflush(stdout);
1202 }
1203
1204
1205 /*--------------------------------------------------------*/
1206 classMeth findNativeMethodCalls(utf *c, utf *m, utf *d ) 
1207 {
1208     int i = 0;
1209     int j = 0;
1210     int cnt = 0;
1211     classMeth mc;
1212     mc.i_class = i;
1213     mc.j_method = j;
1214     mc.methCnt = cnt;
1215
1216     return mc;
1217 }
1218
1219 /*--------------------------------------------------------*/
1220 nativeCall* findNativeClassCalls(char *aclassname ) {
1221 int i;
1222
1223 for (i=0;i<NATIVECALLSSIZE; i++) {
1224    /* convert table to utf later to speed up search */ 
1225    if (strcmp(nativeCalls[i].classname, aclassname) == 0) 
1226         return &nativeCalls[i];
1227    }
1228
1229 return NULL;
1230 }
1231 /*--------------------------------------------------------*/
1232 /*--------------------------------------------------------*/
1233 void utfNativeCall(nativeCall nc, nativeCompCall *ncc) {
1234   int i,j;
1235
1236
1237   ncc->classname = utf_new_char(nc.classname); 
1238   ncc->methCnt = nc.methCnt;
1239   
1240   for (i=0; i<nc.methCnt; i++) {  
1241     ncc->methods[i].methodname = utf_new_char(nc.methods[i].methodname);
1242     ncc->methods[i].descriptor = utf_new_char(nc.methods[i].descriptor);
1243     ncc->callCnt[i] = nc.callCnt[i];
1244
1245     for (j=0; j<nc.callCnt[i]; j++) {  
1246
1247         ncc->methods[i].methodCalls[j].classname  = utf_new_char(nc.methods[i].methodCalls[j].classname);
1248
1249         if (strcmp("", nc.methods[i].methodCalls[j].methodname) != 0) {
1250           ncc->methods[i].methodCalls[j].methodname = utf_new_char(nc.methods[i].methodCalls[j].methodname);
1251           ncc->methods[i].methodCalls[j].descriptor = utf_new_char(nc.methods[i].methodCalls[j].descriptor);
1252           }
1253         else {
1254           ncc->methods[i].methodCalls[j].methodname = NULL;
1255           ncc->methods[i].methodCalls[j].descriptor = NULL;
1256           }
1257       }
1258     }
1259 }
1260
1261
1262
1263 /*--------------------------------------------------------*/
1264
1265 bool natcall2utf(bool natcallcompdone) {
1266 int i;
1267
1268 if (natcallcompdone) 
1269         return true;
1270
1271 for (i=0;i<NATIVECALLSSIZE; i++) {
1272    utfNativeCall  (nativeCalls[i], &nativeCompCalls[i]);  
1273    }
1274
1275 return true;
1276 }
1277
1278 /*
1279  * These are local overrides for various environment variables in Emacs.
1280  * Please do not remove this and leave it at the end of the file, where
1281  * Emacs will automagically detect them.
1282  * ---------------------------------------------------------------------
1283  * Local variables:
1284  * mode: c
1285  * indent-tabs-mode: t
1286  * c-basic-offset: 4
1287  * tab-width: 4
1288  * End:
1289  */