* src/native/native.c (native_resolve_function): Renamed to
[cacao.git] / src / native / native.c
1 /* src/native/native.c - table of native functions
2
3    Copyright (C) 1996-2005, 2006, 2007 R. Grafl, A. Krall, C. Kruegel,
4    C. Oates, R. Obermaisser, M. Platter, M. Probst, S. Ring,
5    E. Steiner, C. Thalinger, D. Thuernbeck, P. Tomsich, C. Ullrich,
6    J. Wenninger, 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., 51 Franklin Street, Fifth Floor, Boston, MA
23    02110-1301, USA.
24
25 */
26
27
28 #include "config.h"
29
30 #include <assert.h>
31 #include <ctype.h>
32
33 #if defined(ENABLE_LTDL) && defined(HAVE_LTDL_H)
34 # include <ltdl.h>
35 #endif
36
37 #include <stdint.h>
38
39 #include "vm/types.h"
40
41 #include "mm/memory.h"
42
43 #include "native/jni.h"
44 #include "native/native.h"
45
46 #include "native/vm/nativevm.h"
47
48 #include "threads/lock-common.h"
49
50 #include "toolbox/avl.h"
51 #include "toolbox/hashtable.h"
52 #include "toolbox/logging.h"
53
54 #include "vm/builtin.h"
55 #include "vm/exceptions.h"
56 #include "vm/global.h"
57 #include "vm/stringlocal.h"
58 #include "vm/vm.h"
59
60 #include "vm/jit/asmpart.h"
61 #include "vm/jit/jit.h"
62
63 #include "vmcore/loader.h"
64 #include "vmcore/options.h"
65 #include "vm/resolve.h"
66
67 #if defined(ENABLE_JVMTI)
68 #include "native/jvmti/cacaodbg.h"
69 #endif
70
71
72 /* global variables ***********************************************************/
73
74 static avl_tree_t *tree_native_methods;
75
76 #if defined(ENABLE_LTDL)
77 static hashtable *hashtable_library;
78 #endif
79
80
81 /* prototypes *****************************************************************/
82
83 static s4 native_tree_native_methods_comparator(const void *treenode, const void *node);
84
85
86 /* native_init *****************************************************************
87
88    Initializes the native subsystem.
89
90 *******************************************************************************/
91
92 bool native_init(void)
93 {
94 #if defined(ENABLE_LTDL)
95         /* initialize libltdl */
96
97         if (lt_dlinit())
98                 vm_abort("native_init: lt_dlinit failed: %s\n", lt_dlerror());
99
100         /* initialize library hashtable, 10 entries should be enough */
101
102         hashtable_library = NEW(hashtable);
103
104         hashtable_create(hashtable_library, 10);
105 #endif
106
107         /* initialize the native methods table */
108
109         tree_native_methods = avl_create(&native_tree_native_methods_comparator);
110
111         /* everything's ok */
112
113         return true;
114 }
115
116
117 /* native_tree_native_methods_comparator ***************************************
118
119    Comparison function for AVL tree of native methods.
120
121    IN:
122        treenode....node in the tree
123            node........node to compare with tree-node
124
125    RETURN VALUE:
126        -1, 0, +1
127
128 *******************************************************************************/
129
130 static s4 native_tree_native_methods_comparator(const void *treenode, const void *node)
131 {
132         const native_methods_node_t *treenmn;
133         const native_methods_node_t *nmn;
134
135         treenmn = treenode;
136         nmn     = node;
137
138         /* these are for walking the tree */
139
140         if (treenmn->classname < nmn->classname)
141                 return -1;
142         else if (treenmn->classname > nmn->classname)
143                 return 1;
144
145         if (treenmn->name < nmn->name)
146                 return -1;
147         else if (treenmn->name > nmn->name)
148                 return 1;
149
150         if (treenmn->descriptor < nmn->descriptor)
151                 return -1;
152         else if (treenmn->descriptor > nmn->descriptor)
153                 return 1;
154
155         /* all pointers are equal, we have found the entry */
156
157         return 0;
158 }
159
160
161 /* native_make_overloaded_function *********************************************
162
163    XXX
164
165 *******************************************************************************/
166
167 static utf *native_make_overloaded_function(utf *name, utf *descriptor)
168 {
169         char *newname;
170         s4    namelen;
171         char *utf_ptr;
172         u2    c;
173         s4    i;
174         s4    dumpsize;
175         utf  *u;
176
177         /* mark memory */
178
179         dumpsize = dump_size();
180
181         utf_ptr = descriptor->text;
182         namelen = strlen(name->text) + strlen("__") + strlen("0");
183
184         /* calculate additional length */
185
186         while ((c = utf_nextu2(&utf_ptr)) != ')') {
187                 switch (c) {
188                 case 'Z':
189                 case 'B':
190                 case 'C':
191                 case 'S':
192                 case 'I':
193                 case 'J':
194                 case 'F':
195                 case 'D':
196                         namelen++;
197                         break;
198                 case '[':
199                         namelen += 2;
200                         break;
201                 case 'L':
202                         namelen++;
203                         while (utf_nextu2(&utf_ptr) != ';')
204                                 namelen++;
205                         namelen += 2;
206                         break;
207                 case '(':
208                         break;
209                 default:
210                         assert(0);
211                 }
212         }
213
214         /* reallocate memory */
215
216         i = strlen(name->text);
217
218         newname = DMNEW(char, namelen);
219         MCOPY(newname, name->text, char, i);
220
221         utf_ptr = descriptor->text;
222
223         newname[i++] = '_';
224         newname[i++] = '_';
225
226         while ((c = utf_nextu2(&utf_ptr)) != ')') {
227                 switch (c) {
228                 case 'Z':
229                 case 'B':
230                 case 'C':
231                 case 'S':
232                 case 'J':
233                 case 'I':
234                 case 'F':
235                 case 'D':
236                         newname[i++] = c;
237                         break;
238                 case '[':
239                         newname[i++] = '_';
240                         newname[i++] = '3';
241                         break;
242                 case 'L':
243                         newname[i++] = 'L';
244                         while ((c = utf_nextu2(&utf_ptr)) != ';')
245                                 if (((c >= 'a') && (c <= 'z')) ||
246                                         ((c >= 'A') && (c <= 'Z')) ||
247                                         ((c >= '0') && (c <= '9')))
248                                         newname[i++] = c;
249                                 else
250                                         newname[i++] = '_';
251                         newname[i++] = '_';
252                         newname[i++] = '2';
253                         break;
254                 case '(':
255                         break;
256                 default:
257                         assert(0);
258                 }
259         }
260
261         /* close string */
262
263         newname[i] = '\0';
264
265         /* make a utf-string */
266
267         u = utf_new_char(newname);
268
269         /* release memory */
270
271         dump_release(dumpsize);
272
273         return u;
274 }
275
276
277 /* native_insert_char **********************************************************
278
279    Inserts the passed UTF character into the native method name.  If
280    necessary it is escaped properly.
281
282 *******************************************************************************/
283
284 static s4 native_insert_char(char *name, u4 pos, u2 c)
285 {
286         s4 val;
287         s4 i;
288
289         switch (c) {
290         case '/':
291         case '.':
292                 /* replace '/' or '.' with '_' */
293                 name[pos] = '_';
294                 break;
295
296         case '_':
297                 /* escape sequence for '_' is '_1' */
298                 name[pos]   = '_';
299                 name[++pos] = '1';
300                 break;
301
302         case ';':
303                 /* escape sequence for ';' is '_2' */
304                 name[pos]   = '_';
305                 name[++pos] = '2';
306                 break;
307
308         case '[':
309                 /* escape sequence for '[' is '_1' */
310                 name[pos]   = '_';
311                 name[++pos] = '3';
312                 break;
313
314         default:
315                 if (isalnum(c))
316                         name[pos] = c;
317                 else {
318                         /* unicode character */
319                         name[pos]   = '_';
320                         name[++pos] = '0';
321
322                         for (i = 0; i < 4; ++i) {
323                                 val = c & 0x0f;
324                                 name[pos + 4 - i] = (val > 10) ? ('a' + val - 10) : ('0' + val);
325                                 c >>= 4;
326                         }
327
328                         pos += 4;
329                 }
330                 break;
331         }
332
333         /* return the new buffer index */
334
335         return pos;
336 }
337
338
339 /* native_method_symbol ********************************************************
340
341    Generate a method-symbol string out of the class name and the
342    method name.
343
344 *******************************************************************************/
345
346 static utf *native_method_symbol(utf *classname, utf *methodname)
347 {
348         char *name;
349         s4    namelen;
350         char *utf_ptr;
351         char *utf_endptr;
352         u2    c;
353         u4    pos;
354         s4    dumpsize;
355         utf  *u;
356
357         /* mark memory */
358
359         dumpsize = dump_size();
360
361         /* Calculate length of native function name.  We multiply the
362            class and method name length by 6 as this is the maxium
363            escape-sequence that can be generated (unicode). */
364
365         namelen =
366                 strlen("Java_") +
367                 utf_get_number_of_u2s(classname) * 6 +
368                 strlen("_") +
369                 utf_get_number_of_u2s(methodname) * 6 +
370                 strlen("0");
371
372         /* allocate memory */
373
374         name = DMNEW(char, namelen);
375
376         /* generate name of native functions */
377
378         strcpy(name, "Java_");
379         pos = strlen("Java_");
380
381         utf_ptr    = classname->text;
382         utf_endptr = UTF_END(classname);
383
384         for (; utf_ptr < utf_endptr; utf_ptr++, pos++) {
385                 c   = *utf_ptr;
386                 pos = native_insert_char(name, pos, c);
387         }
388
389         /* seperator between class and method */
390
391         name[pos++] = '_';
392
393         utf_ptr    = methodname->text;
394         utf_endptr = UTF_END(methodname);
395
396         for (; utf_ptr < utf_endptr; utf_ptr++, pos++) {
397                 c   = *utf_ptr;
398                 pos = native_insert_char(name, pos, c);
399         }
400
401         /* close string */
402
403         name[pos] = '\0';
404
405         /* check for an buffer overflow */
406
407         assert(pos <= namelen);
408
409         /* make a utf-string */
410
411         u = utf_new_char(name);
412
413         /* release memory */
414
415         dump_release(dumpsize);
416
417         return u;
418 }
419
420
421 /* native_method_register ******************************************************
422
423    Register a native method in the native method table.
424
425 *******************************************************************************/
426
427 void native_method_register(utf *classname, const JNINativeMethod *methods,
428                                                         int32_t count)
429 {
430         native_methods_node_t *nmn;
431         utf                   *name;
432         utf                   *descriptor;
433         int32_t                i;
434
435         /* insert all methods passed */
436
437         for (i = 0; i < count; i++) {
438                 if (opt_verbosejni) {
439                         printf("[Registering JNI native method ");
440                         utf_display_printable_ascii_classname(classname);
441                         printf(".%s]\n", methods[i].name);
442                 }
443
444                 /* generate the utf8 names */
445
446                 name       = utf_new_char(methods[i].name);
447                 descriptor = utf_new_char(methods[i].signature);
448
449                 /* allocate a new tree node */
450
451                 nmn = NEW(native_methods_node_t);
452
453                 nmn->classname  = classname;
454                 nmn->name       = name;
455                 nmn->descriptor = descriptor;
456                 nmn->function   = (functionptr) (ptrint) methods[i].fnPtr;
457
458                 /* insert the method into the tree */
459
460                 avl_insert(tree_native_methods, nmn);
461         }
462 }
463
464
465 /* native_method_find **********************************************************
466
467    Find a native method in the native method table.
468
469 *******************************************************************************/
470
471 static functionptr native_method_find(methodinfo *m)
472 {
473         native_methods_node_t  tmpnmn;
474         native_methods_node_t *nmn;
475
476         /* fill the temporary structure used for searching the tree */
477
478         tmpnmn.classname  = m->class->name;
479         tmpnmn.name       = m->name;
480         tmpnmn.descriptor = m->descriptor;
481
482         /* find the entry in the AVL-tree */
483
484         nmn = avl_find(tree_native_methods, &tmpnmn);
485
486         if (nmn == NULL)
487                 return NULL;
488
489         return nmn->function;
490 }
491
492
493 /* native_method_resolve *******************************************************
494
495    Resolves a native method, maybe from a dynamic library.
496
497    IN:
498        m ... methodinfo of the native Java method to resolve
499
500    RESULT:
501        pointer to the resolved method (symbol)
502
503 *******************************************************************************/
504
505 functionptr native_method_resolve(methodinfo *m)
506 {
507         utf                            *name;
508         utf                            *newname;
509         functionptr                     f;
510 #if defined(ENABLE_LTDL)
511         classloader                    *cl;
512         hashtable_library_loader_entry *le;
513         hashtable_library_name_entry   *ne;
514         u4                              key;    /* hashkey                        */
515         u4                              slot;   /* slot in hashtable              */
516 #endif
517 #if defined(WITH_CLASSPATH_SUN)
518         methodinfo                     *method_findNative;
519         java_handle_t                  *s;
520 #endif
521
522         /* verbose output */
523
524         if (opt_verbosejni) {
525                 printf("[Dynamic-linking native method ");
526                 utf_display_printable_ascii_classname(m->class->name);
527                 printf(".");
528                 utf_display_printable_ascii(m->name);
529                 printf(" ... ");
530         }
531
532         /* generate method symbol string */
533
534         name = native_method_symbol(m->class->name, m->name);
535
536         /* generate overloaded function (having the types in it's name)           */
537
538         newname = native_make_overloaded_function(name, m->descriptor);
539
540         /* check the library hash entries of the classloader of the
541            methods's class  */
542
543         f = NULL;
544
545 #if defined(ENABLE_LTDL)
546         /* Get the classloader. */
547
548         cl = class_get_classloader(m->class);
549
550         /* normally addresses are aligned to 4, 8 or 16 bytes */
551
552         key  = ((u4) (ptrint) cl) >> 4;                       /* align to 16-byte */
553         slot = key & (hashtable_library->size - 1);
554         le   = hashtable_library->ptr[slot];
555
556         /* iterate through loaders in this hash slot */
557
558         while ((le != NULL) && (f == NULL)) {
559                 /* iterate through names in this loader */
560
561                 ne = le->namelink;
562                         
563                 while ((ne != NULL) && (f == NULL)) {
564                         f = (functionptr) (ptrint) lt_dlsym(ne->handle, name->text);
565
566                         if (f == NULL)
567                                 f = (functionptr) (ptrint) lt_dlsym(ne->handle, newname->text);
568
569                         ne = ne->hashlink;
570                 }
571
572                 le = le->hashlink;
573         }
574
575 # if defined(WITH_CLASSPATH_SUN)
576         if (f == NULL) {
577                 /* We can resolve the function directly from
578                    java.lang.ClassLoader as it's a static function. */
579                 /* XXX should be done in native_init */
580
581                 method_findNative =
582                         class_resolveclassmethod(class_java_lang_ClassLoader,
583                                                                          utf_findNative,
584                                                                          utf_java_lang_ClassLoader_java_lang_String__J,
585                                                                          class_java_lang_ClassLoader,
586                                                                          true);
587
588                 if (method_findNative == NULL)
589                         return NULL;
590
591                 /* try the normal name */
592
593                 s = javastring_new(name);
594
595                 f = (functionptr) (intptr_t) vm_call_method_long(method_findNative,
596                                                                                                                  NULL, cl, s);
597
598                 /* if not found, try the mangled name */
599
600                 if (f == NULL) {
601                         s = javastring_new(newname);
602
603                         f = (functionptr) (intptr_t) vm_call_method_long(method_findNative,
604                                                                                                                          NULL, cl, s);
605                 }
606         }
607 # endif
608
609         if (f != NULL)
610                 if (opt_verbosejni)
611                         printf("JNI ]\n");
612 #endif
613
614         /* If not found, try to find the native function symbol in the
615            main program. */
616
617         if (f == NULL) {
618                 f = native_method_find(m);
619
620                 if (f != NULL)
621                         if (opt_verbosejni)
622                                 printf("internal ]\n");
623         }
624
625 #if defined(ENABLE_JVMTI)
626         /* fire Native Method Bind event */
627         if (jvmti) jvmti_NativeMethodBind(m, f, &f);
628 #endif
629
630         /* no symbol found? throw exception */
631
632         if (f == NULL) {
633                 if (opt_verbosejni)
634                         printf("failed ]\n");
635
636                 exceptions_throw_unsatisfiedlinkerror(m->name);
637         }
638
639         return f;
640 }
641
642
643 /* native_library_open *********************************************************
644
645    Open a native library with the given utf8 name.
646
647 *******************************************************************************/
648
649 #if defined(ENABLE_LTDL)
650 lt_dlhandle native_library_open(utf *filename)
651 {
652         lt_dlhandle handle;
653
654         if (opt_verbosejni) {
655                 printf("[Loading native library ");
656                 utf_display_printable_ascii(filename);
657                 printf(" ... ");
658         }
659
660         /* try to open the library */
661
662         handle = lt_dlopen(filename->text);
663
664         if (handle == NULL) {
665                 if (opt_verbose) {
666                         log_start();
667                         log_print("native_library_load: lt_dlopen failed: ");
668                         log_print(lt_dlerror());
669                         log_finish();
670                 }
671
672                 return NULL;
673         }
674
675         return handle;
676 }
677 #endif
678
679
680 /* native_library_add **********************************************************
681
682    Adds an entry to the native library hashtable.
683
684 *******************************************************************************/
685
686 #if defined(ENABLE_LTDL)
687 void native_library_add(utf *filename, classloader *loader, lt_dlhandle handle)
688 {
689         hashtable_library_loader_entry *le;
690         hashtable_library_name_entry   *ne; /* library name                       */
691         u4   key;                           /* hashkey                            */
692         u4   slot;                          /* slot in hashtable                  */
693
694         LOCK_MONITOR_ENTER(hashtable_library->header);
695
696         /* normally addresses are aligned to 4, 8 or 16 bytes */
697
698         key  = ((u4) (ptrint) loader) >> 4;        /* align to 16-byte boundaries */
699         slot = key & (hashtable_library->size - 1);
700         le   = hashtable_library->ptr[slot];
701
702         /* search external hash chain for the entry */
703
704         while (le) {
705                 if (le->loader == loader)
706                         break;
707
708                 le = le->hashlink;                  /* next element in external chain */
709         }
710
711         /* no loader found? create a new entry */
712
713         if (le == NULL) {
714                 le = NEW(hashtable_library_loader_entry);
715
716                 le->loader   = loader;
717                 le->namelink = NULL;
718
719                 /* insert entry into hashtable */
720
721                 le->hashlink =
722                         (hashtable_library_loader_entry *) hashtable_library->ptr[slot];
723                 hashtable_library->ptr[slot] = le;
724
725                 /* update number of hashtable-entries */
726
727                 hashtable_library->entries++;
728         }
729
730
731         /* search for library name */
732
733         ne = le->namelink;
734
735         while (ne) {
736                 if (ne->name == filename) {
737                         LOCK_MONITOR_EXIT(hashtable_library->header);
738
739                         return;
740                 }
741
742                 ne = ne->hashlink;                  /* next element in external chain */
743         }
744
745         /* not found? add the library name to the classloader */
746
747         ne = NEW(hashtable_library_name_entry);
748
749         ne->name   = filename;
750         ne->handle = handle;
751
752         /* insert entry into external chain */
753
754         ne->hashlink = le->namelink;
755         le->namelink = ne;
756
757         LOCK_MONITOR_EXIT(hashtable_library->header);
758 }
759 #endif
760
761
762 /* native_library_find *********************************************************
763
764    Find an entry in the native library hashtable.
765
766 *******************************************************************************/
767
768 #if defined(ENABLE_LTDL)
769 hashtable_library_name_entry *native_library_find(utf *filename,
770                                                                                                   classloader *loader)
771 {
772         hashtable_library_loader_entry *le;
773         hashtable_library_name_entry   *ne; /* library name                       */
774         u4   key;                           /* hashkey                            */
775         u4   slot;                          /* slot in hashtable                  */
776
777         /* normally addresses are aligned to 4, 8 or 16 bytes */
778
779         key  = ((u4) (ptrint) loader) >> 4;        /* align to 16-byte boundaries */
780         slot = key & (hashtable_library->size - 1);
781         le   = hashtable_library->ptr[slot];
782
783         /* search external hash chain for the entry */
784
785         while (le) {
786                 if (le->loader == loader)
787                         break;
788
789                 le = le->hashlink;                  /* next element in external chain */
790         }
791
792         /* no loader found? return NULL */
793
794         if (le == NULL)
795                 return NULL;
796
797         /* search for library name */
798
799         ne = le->namelink;
800
801         while (ne) {
802                 if (ne->name == filename)
803                         return ne;
804
805                 ne = ne->hashlink;                  /* next element in external chain */
806         }
807
808         /* return entry, if no entry was found, ne is NULL */
809
810         return ne;
811 }
812 #endif
813
814
815 /* native_new_and_init *********************************************************
816
817    Creates a new object on the heap and calls the initializer.
818    Returns the object pointer or NULL if memory is exhausted.
819                         
820 *******************************************************************************/
821
822 java_handle_t *native_new_and_init(classinfo *c)
823 {
824         methodinfo    *m;
825         java_handle_t *o;
826
827         if (c == NULL)
828                 vm_abort("native_new_and_init: c == NULL");
829
830         /* create object */
831
832         o = builtin_new(c);
833         
834         if (o == NULL)
835                 return NULL;
836
837         /* try to find the initializer */
838
839         m = class_findmethod(c, utf_init, utf_void__void);
840                                                       
841         /* ATTENTION: returning the object here is ok, since the class may
842        not have an initializer */
843
844         if (m == NULL)
845                 return o;
846
847         /* call initializer */
848
849         (void) vm_call_method(m, o);
850
851         return o;
852 }
853
854
855 java_handle_t *native_new_and_init_string(classinfo *c, java_handle_t *s)
856 {
857         methodinfo    *m;
858         java_handle_t *o;
859
860         if (c == NULL)
861                 vm_abort("native_new_and_init_string: c == NULL");
862
863         /* create object */
864
865         o = builtin_new(c);
866
867         if (o == NULL)
868                 return NULL;
869
870         /* find initializer */
871
872         m = class_findmethod(c, utf_init, utf_java_lang_String__void);
873
874         /* initializer not found */
875
876         if (m == NULL)
877                 return NULL;
878
879         /* call initializer */
880
881         (void) vm_call_method(m, o, s);
882
883         return o;
884 }
885
886
887 /*
888  * These are local overrides for various environment variables in Emacs.
889  * Please do not remove this and leave it at the end of the file, where
890  * Emacs will automagically detect them.
891  * ---------------------------------------------------------------------
892  * Local variables:
893  * mode: c
894  * indent-tabs-mode: t
895  * c-basic-offset: 4
896  * tab-width: 4
897  * End:
898  * vim:noexpandtab:sw=4:ts=4:
899  */