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