1 /****************************** native.c ***************************************
3 Copyright (c) 1997 A. Krall, R. Grafl, M. Gschwind, M. Probst
5 See file COPYRIGHT for information on usage and disclaimer of warranties
7 Contains the tables for native methods.
8 The .hh files created with the header file generator are all included here
9 as are the C functions implementing these methods.
11 Authors: Reinhard Grafl EMAIL: cacao@complang.tuwien.ac.at
12 Roman Obermaisser EMAIL: cacao@complang.tuwien.ac.at
13 Andreas Krall EMAIL: cacao@complang.tuwien.ac.at
15 Last Change: 1996/11/14
17 *******************************************************************************/
23 #include "nativetypes.hh"
33 #include "threads/thread.h" /* schani */
34 #include "threads/locks.h"
36 /* Include files for IO functions */
40 #include <sys/types.h>
46 #include "../threads/threadio.h"
48 /* searchpath for classfiles */
49 static char *classpath;
51 /* for java-string to char conversion */
52 #define MAXSTRINGSIZE 1000
54 /******************** systemclasses required for native methods ***************/
56 static classinfo *class_java_lang_Class;
57 static classinfo *class_java_lang_Cloneable;
58 static classinfo *class_java_lang_CloneNotSupportedException;
59 static classinfo *class_java_lang_System;
60 static classinfo *class_java_lang_ClassLoader;
61 static classinfo *class_java_lang_ClassNotFoundException;
62 static classinfo *class_java_lang_InstantiationException;
63 static classinfo *class_java_lang_NoSuchMethodError;
64 static classinfo *class_java_lang_NoSuchFieldError;
65 static classinfo *class_java_lang_ClassFormatError;
66 static classinfo *class_java_lang_IllegalArgumentException;
67 static classinfo *class_java_lang_ArrayIndexOutOfBoundsException;
68 static classinfo *class_java_lang_NoSuchFieldException;
69 static classinfo *class_java_io_SyncFailedException;
70 static classinfo *class_java_io_IOException;
71 static classinfo *class_java_io_UnixFileSystem;
72 static classinfo *class_java_security_PrivilegedActionException;
73 static classinfo *class_java_net_UnknownHostException;
74 static classinfo *class_java_net_SocketException;
75 static classinfo *class_java_lang_NoSuchMethodException;
76 static classinfo *class_java_lang_Double;
77 static classinfo *class_java_lang_Float;
78 static classinfo *class_java_lang_Long;
79 static classinfo *class_java_lang_Byte;
80 static classinfo *class_java_lang_Short;
81 static classinfo *class_java_lang_Boolean;
82 static classinfo *class_java_lang_Void;
83 static classinfo *class_java_lang_Character;
84 static classinfo *class_java_lang_Integer;
86 /* the system classloader object */
87 struct java_lang_ClassLoader *SystemClassLoader = NULL;
89 /* for raising exceptions from native methods */
90 java_objectheader* exceptionptr = NULL;
92 /************* use classinfo structure as java.lang.Class object **************/
94 static void use_class_as_object (classinfo *c)
96 c->header.vftbl = class_java_lang_Class -> vftbl;
99 /*********************** include Java Native Interface ************************/
103 /*************************** include native methods ***************************/
105 #include "nat/Object.c"
106 #include "nat/String.c"
107 #include "nat/ClassLoader.c"
108 #include "nat/Class.c"
109 #include "nat/Compiler.c"
110 #include "nat/Double.c"
111 #include "nat/Float.c"
112 #include "nat/Math.c"
113 #include "nat/Package.c"
114 #include "nat/Runtime.c"
115 #include "nat/SecurityManager.c"
116 #include "nat/System.c"
117 #include "nat/Thread.c"
118 #include "nat/Throwable.c"
119 #include "nat/Finalizer.c"
120 #include "nat/Array.c"
121 #include "nat/Constructor.c"
122 #include "nat/Field.c"
123 #include "nat/Method.c"
124 #include "nat/FileDescriptor.c"
125 #include "nat/FileInputStream.c"
126 #include "nat/FileOutputStream.c"
127 #include "nat/FileSystem.c"
128 #include "nat/ObjectInputStream.c"
129 #include "nat/ObjectStreamClass.c"
130 #include "nat/RandomAccessFile.c"
131 #include "nat/ResourceBundle.c"
132 #include "nat/JarFile.c"
133 #include "nat/Adler32.c"
134 #include "nat/CRC32.c"
135 #include "nat/Deflater.c"
136 #include "nat/Inflater.c"
137 #include "nat/ZipEntry.c"
138 #include "nat/ZipFile.c"
139 #include "nat/BigInteger.c"
140 #include "nat/InetAddress.c"
141 #include "nat/InetAddressImpl.c"
142 #include "nat/DatagramPacket.c"
143 #include "nat/PlainDatagramSocketImpl.c"
144 #include "nat/PlainSocketImpl.c"
145 #include "nat/SocketInputStream.c"
146 #include "nat/SocketOutputStream.c"
147 #include "nat/AccessController.c"
148 #include "nat/ClassLoader_NativeLibrary.c"
149 #include "nat/UnixFileSystem.c"
151 /************************** tables for methods ********************************/
153 /* table for locating native methods */
154 static struct nativeref {
162 #include "nativetable.hh"
167 #define NATIVETABLESIZE (sizeof(nativetable)/sizeof(struct nativeref))
169 /* table for fast string comparison */
170 static struct nativecompref {
176 } nativecomptable [NATIVETABLESIZE];
178 /* string comparsion table initialized */
179 static bool nativecompdone = false;
182 /*********************** function: native_loadclasses **************************
184 load classes required for native methods
186 *******************************************************************************/
188 void native_loadclasses()
190 /* class_new adds the class to the list of classes to be loaded */
191 class_java_lang_Cloneable =
192 class_new ( utf_new_char ("java/lang/Cloneable") );
193 class_java_lang_CloneNotSupportedException =
194 class_new ( utf_new_char ("java/lang/CloneNotSupportedException") );
195 class_java_lang_Class =
196 class_new ( utf_new_char ("java/lang/Class") );
197 class_java_io_IOException =
198 class_new ( utf_new_char ("java/io/IOException") );
199 class_java_lang_ClassNotFoundException =
200 class_new ( utf_new_char ("java/lang/ClassNotFoundException") );
201 class_java_lang_InstantiationException =
202 class_new ( utf_new_char ("java/lang/InstantiationException") );
203 class_java_lang_NoSuchMethodError =
204 class_new ( utf_new_char ("java/lang/NoSuchMethodError") );
205 class_java_lang_NoSuchFieldError =
206 class_new ( utf_new_char ("java/lang/NoSuchFieldError") );
207 class_java_lang_ClassFormatError =
208 class_new ( utf_new_char ("java/lang/ClassFormatError") );
209 class_java_io_SyncFailedException =
210 class_new ( utf_new_char ("java/io/SyncFailedException") );
211 class_java_io_UnixFileSystem =
212 class_new ( utf_new_char ("java/io/UnixFileSystem") );
213 class_java_lang_System =
214 class_new ( utf_new_char ("java/lang/System") );
215 class_java_lang_ClassLoader =
216 class_new ( utf_new_char ("java/lang/ClassLoader") );
217 class_java_security_PrivilegedActionException =
218 class_new( utf_new_char("java/security/PrivilegedActionException"));
219 class_java_net_UnknownHostException =
220 loader_load( utf_new_char ("java/net/UnknownHostException") );
221 class_java_net_SocketException =
222 loader_load( utf_new_char ("java/net/SocketException") );
223 class_java_lang_IllegalArgumentException =
224 class_new( utf_new_char("java/lang/IllegalArgumentException"));
225 class_java_lang_ArrayIndexOutOfBoundsException =
226 class_new( utf_new_char ("java/lang/ArrayIndexOutOfBoundsException") );
227 class_java_lang_NoSuchFieldException =
228 class_new( utf_new_char ("java/lang/NoSuchFieldException") );
229 class_java_lang_NoSuchMethodException =
230 class_new( utf_new_char ("java/lang/NoSuchMethodException") );
232 /* load classes for wrapping primitive types */
233 class_java_lang_Double =
234 class_new( utf_new_char ("java/lang/Double") );
235 class_java_lang_Float =
236 class_new( utf_new_char ("java/lang/Float") );
237 class_java_lang_Character =
238 class_new( utf_new_char ("java/lang/Character") );
239 class_java_lang_Integer =
240 class_new( utf_new_char ("java/lang/Integer") );
241 class_java_lang_Long =
242 class_new( utf_new_char ("java/lang/Long") );
243 class_java_lang_Byte =
244 class_new( utf_new_char ("java/lang/Byte") );
245 class_java_lang_Short =
246 class_new( utf_new_char ("java/lang/Short") );
247 class_java_lang_Boolean =
248 class_new( utf_new_char ("java/lang/Boolean") );
249 class_java_lang_Void =
250 class_new( utf_new_char ("java/lang/Void") );
252 /* load to avoid dynamic classloading */
253 class_new(utf_new_char("sun/net/www/protocol/file/Handler"));
254 class_new(utf_new_char("sun/net/www/protocol/jar/Handler"));
255 class_new(utf_new_char("sun/io/CharToByteISO8859_1"));
257 /* start classloader */
258 loader_load(utf_new_char("sun/io/ByteToCharISO8859_1"));
262 /*************** adds a class to the vector of loaded classes ****************/
264 void systemclassloader_addclass(classinfo *c)
268 /* find method addClass of java.lang.ClassLoader */
269 m = class_resolvemethod (
270 class_java_lang_ClassLoader,
271 utf_new_char("addClass"),
272 utf_new_char("(Ljava/lang/Class;)")
275 if (!m) panic("warning: cannot initialize classloader");
277 /* prepare class to be passed as argument */
278 use_class_as_object (c);
280 /* call 'addClass' */
281 asm_calljavamethod(m,
282 (java_objectheader*) SystemClassLoader,
283 (java_objectheader*) c,
289 /*************** adds a library to the vector of loaded libraries *************/
291 void systemclassloader_addlibrary(java_objectheader *o)
295 /* find method addElement of java.util.Vector */
296 m = class_resolvemethod (
297 loader_load ( utf_new_char ("java/util/Vector") ),
298 utf_new_char("addElement"),
299 utf_new_char("(Ljava/lang/Object;)V")
302 if (!m) panic("cannot initialize classloader");
304 /* call 'addElement' */
305 asm_calljavamethod(m,
306 SystemClassLoader->nativeLibraries,
313 /*****************************************************************************
315 create systemclassloader object and initialize instance fields
317 ******************************************************************************/
319 void init_systemclassloader()
321 if (!SystemClassLoader) {
323 /* create object and call initializer */
324 SystemClassLoader = (java_lang_ClassLoader*) native_new_and_init(class_java_lang_ClassLoader);
325 heap_addreference((void**) &SystemClassLoader);
327 /* systemclassloader has no parent */
328 SystemClassLoader->parent = NULL;
329 SystemClassLoader->initialized = true;
334 /********************* add loaded library name *******************************/
336 void systemclassloader_addlibname(java_objectheader *o)
339 java_objectheader *LibraryNameVector;
342 m = class_resolvemethod (
343 loader_load ( utf_new_char ("java/util/Vector") ),
344 utf_new_char("addElement"),
345 utf_new_char("(Ljava/lang/Object;)V")
348 if (!m) panic("cannot initialize classloader");
350 id = env.GetStaticFieldID(&env,class_java_lang_ClassLoader,"loadedLibraryNames","Ljava/util/Vector;");
351 if (!id) panic("can not access ClassLoader");
353 asm_calljavamethod(m,
354 GetStaticObjectField(&env,class_java_lang_ClassLoader,id),
362 /********************* function: native_setclasspath **************************/
364 void native_setclasspath (char *path)
366 /* set searchpath for classfiles */
370 /***************** function: throw_classnotfoundexception *********************/
372 void throw_classnotfoundexception()
374 /* throws a ClassNotFoundException */
375 exceptionptr = native_new_and_init (class_java_lang_ClassNotFoundException);
379 /*********************** Function: native_findfunction *************************
381 Looks up a method (must have the same class name, method name, descriptor
382 and 'static'ness) and returns a function pointer to it.
383 Returns: function pointer or NULL (if there is no such method)
385 Remark: For faster operation, the names/descriptors are converted from C
386 strings to Unicode the first time this function is called.
388 *******************************************************************************/
390 functionptr native_findfunction (utf *cname, utf *mname,
391 utf *desc, bool isstatic)
394 /* entry of table for fast string comparison */
395 struct nativecompref *n;
396 /* for warning message if no function is found */
400 isstatic = isstatic ? true : false;
402 if (!nativecompdone) {
403 for (i = 0; i < NATIVETABLESIZE; i++) {
404 nativecomptable[i].classname =
405 utf_new_char(nativetable[i].classname);
406 nativecomptable[i].methodname =
407 utf_new_char(nativetable[i].methodname);
408 nativecomptable[i].descriptor =
409 utf_new_char(nativetable[i].descriptor);
410 nativecomptable[i].isstatic =
411 nativetable[i].isstatic;
412 nativecomptable[i].func =
415 nativecompdone = true;
418 for (i = 0; i < NATIVETABLESIZE; i++) {
419 n = &(nativecomptable[i]);
421 if (cname == n->classname && mname == n->methodname &&
422 desc == n->descriptor && isstatic == n->isstatic)
426 /* no function was found, display warning */
429 utf_strlen(cname) + utf_strlen(mname) + utf_strlen(desc) + 64;
431 buffer = MNEW(char, buffer_len);
433 strcpy(buffer, "warning: native function ");
434 utf_sprint(buffer+strlen(buffer), mname);
435 strcpy(buffer+strlen(buffer), ": ");
436 utf_sprint(buffer+strlen(buffer), desc);
437 strcpy(buffer+strlen(buffer), " not found in class ");
438 utf_sprint(buffer+strlen(buffer), cname);
442 MFREE(buffer, char, buffer_len);
448 /********************** function: javastring_new *******************************
450 creates a new object of type java/lang/String with the text of
451 the specified utf8-string
453 return: pointer to the string or NULL if memory is exhausted.
455 *******************************************************************************/
457 java_objectheader *javastring_new (utf *u)
459 char *utf_ptr = u->text; /* current utf character in utf string */
460 int utflength = utf_strlen(u); /* length of utf-string if uncompressed */
461 java_lang_String *s; /* result-string */
465 s = (java_lang_String*) builtin_new (class_java_lang_String);
466 a = builtin_newarray_char (utflength);
468 /* javastring or character-array could not be created */
472 /* decompress utf-string */
473 for (i = 0; i < utflength; i++)
474 a->data[i] = utf_nextu2(&utf_ptr);
476 /* set fields of the javastring-object */
479 s -> count = utflength;
481 return (java_objectheader*) s;
484 /********************** function: javastring_new_char **************************
486 creates a new java/lang/String object which contains the convertet
487 C-string passed via text.
489 return: the object pointer or NULL if memory is exhausted.
491 *******************************************************************************/
493 java_objectheader *javastring_new_char (char *text)
496 s4 len = strlen(text); /* length of the string */
497 java_lang_String *s; /* result-string */
500 s = (java_lang_String*) builtin_new (class_java_lang_String);
501 a = builtin_newarray_char (len);
503 /* javastring or character-array could not be created */
504 if ((!a) || (!s)) return NULL;
507 for (i = 0; i < len; i++)
508 a->data[i] = text[i];
510 /* set fields of the javastring-object */
515 return (java_objectheader*) s;
519 /************************* function javastring_tochar **************************
521 converts a Java string into a C string.
523 return: pointer to C string
525 Caution: every call of this function overwrites the previous string !!!
527 *******************************************************************************/
529 static char stringbuffer[MAXSTRINGSIZE];
531 char *javastring_tochar (java_objectheader *so)
533 java_lang_String *s = (java_lang_String*) so;
542 if (s->count > MAXSTRINGSIZE)
544 for (i = 0; i < s->count; i++)
545 stringbuffer[i] = a->data[s->offset+i];
546 stringbuffer[i] = '\0';
551 /****************** function class_findfield_approx ****************************
553 searches in 'classinfo'-structure for a field with the
556 *******************************************************************************/
558 fieldinfo *class_findfield_approx (classinfo *c, utf *name)
561 for (i = 0; i < c->fieldscount; i++) {
562 /* compare field names */
563 if ((c->fields[i].name == name))
564 return &(c->fields[i]);
567 /* field was not found, raise exception */
568 exceptionptr = native_new_and_init(class_java_lang_NoSuchFieldException);
573 /********************** function: native_new_and_init *************************
575 Creates a new object on the heap and calls the initializer.
576 Returns the object pointer or NULL if memory is exhausted.
578 *******************************************************************************/
580 java_objectheader *native_new_and_init (classinfo *c)
583 java_objectheader *o = builtin_new (c); /* create object */
587 /* find initializer */
589 m = class_findmethod(c, utf_new_char("<init>"), utf_new_char("()V"));
591 if (!m) { /* initializer not found */
593 sprintf(logtext, "Warning: class has no instance-initializer: ");
594 utf_sprint(logtext + strlen(logtext), c->name);
600 /* call initializer */
602 asm_calljavamethod (m, o, NULL, NULL, NULL);
606 /******************** function: stringtable_update ****************************
608 traverses the javastring hashtable and sets the vftbl-entries of
609 javastrings which were temporarily set to NULL, because
610 java.lang.Object was not yet loaded
612 *******************************************************************************/
614 void stringtable_update ()
616 java_lang_String *js;
618 literalstring *s; /* hashtable entry */
621 for (i = 0; i < string_hash.size; i++) {
622 s = string_hash.ptr[i];
626 js = (java_lang_String *) s->string;
628 if (!js || !(a = js->value))
629 /* error in hashtable found */
630 panic("invalid literalstring in hashtable");
632 if (!js->header.vftbl)
633 /* vftbl of javastring is NULL */
634 js->header.vftbl = class_java_lang_String -> vftbl;
636 if (!a->header.objheader.vftbl)
637 /* vftbl of character-array is NULL */
638 a->header.objheader.vftbl = class_array -> vftbl;
640 /* follow link in external hash chain */
648 /************************* function: u2_utflength ***************************
650 returns the utf length in bytes of a u2 array
652 *****************************************************************************/
655 u4 u2_utflength(u2 *text, u4 u2_length)
657 u4 result_len = 0; /* utf length in bytes */
658 u2 ch; /* current unicode character */
661 for (len = 0; len < u2_length; len++) {
663 /* next unicode character */
666 /* determine bytes required to store unicode character as utf */
667 if (ch && (ch < 0x80))
678 /********************* function: utf_new_u2 ***********************************
680 make utf symbol from u2 array,
681 if isclassname is true '.' is replaced by '/'
683 *******************************************************************************/
685 utf *utf_new_u2(u2 *unicode_pos, u4 unicode_length, bool isclassname)
687 char *buffer; /* memory buffer for unicode characters */
688 char *pos; /* pointer to current position in buffer */
689 u4 left; /* unicode characters left */
690 u4 buflength; /* utf length in bytes of the u2 array */
691 utf *result; /* resulting utf-string */
694 /* determine utf length in bytes and allocate memory */
695 buflength = u2_utflength(unicode_pos, unicode_length);
696 buffer = MNEW(char,buflength);
698 /* memory allocation failed */
699 if (!buffer) return NULL;
704 for (i = 0; i++ < unicode_length; unicode_pos++) {
705 /* next unicode character */
708 if ((c != 0) && (c < 0x80)) {
711 if ((int) left < 0) break;
712 /* convert classname */
713 if (isclassname && c=='.')
717 } else if (c < 0x800) {
719 unsigned char high = c >> 6;
720 unsigned char low = c & 0x3F;
722 if ((int) left < 0) break;
723 *pos++ = high | 0xC0;
728 char mid = (c >> 6) & 0x3F;
731 if ((int) left < 0) break;
732 *pos++ = high | 0xE0;
738 /* insert utf-string into symbol-table */
739 result = utf_new(buffer,buflength);
740 MFREE(buffer, char, buflength);
744 /********************* function: javastring_toutf *****************************
746 make utf symbol from javastring
748 *******************************************************************************/
750 utf *javastring_toutf(java_lang_String *string, bool isclassname)
752 java_lang_String *str = (java_lang_String *) string;
753 return utf_new_u2(str->value->data,str->count, isclassname);
756 /********************* function: literalstring_u2 *****************************
758 searches for the javastring with the specified u2-array in
759 the string hashtable, if there is no such string a new one is
762 if copymode is true a copy of the u2-array is made
764 *******************************************************************************/
766 java_objectheader *literalstring_u2 (java_chararray *a, u4 length, bool copymode )
768 literalstring *s; /* hashtable element */
769 java_lang_String *js; /* u2-array wrapped in javastring */
770 java_chararray *stringdata; /* copy of u2-array */
775 /* find location in hashtable */
776 key = unicode_hashkey (a->data, length);
777 slot = key & (string_hash.size-1);
778 s = string_hash.ptr[slot];
782 js = (java_lang_String *) s->string;
784 if (js->count == length) {
786 for (i=0; i<length; i++)
787 if (js->value->data[i] != a->data[i]) goto nomatch;
789 /* string already in hashtable, free memory */
791 lit_mem_free(a, sizeof(java_chararray) + sizeof(u2)*(length-1)+10);
793 return (java_objectheader *) js;
797 /* follow link in external hash chain */
802 /* create copy of u2-array for new javastring */
803 u4 arraysize = sizeof(java_chararray) + sizeof(u2)*(length-1)+10;
804 stringdata = lit_mem_alloc ( arraysize );
805 memcpy(stringdata, a, arraysize );
810 /* location in hashtable found, complete arrayheader */
811 if (class_array==NULL) panic("class_array not initialized");
812 stringdata -> header.objheader.vftbl = class_array -> vftbl;
813 stringdata -> header.size = length;
814 stringdata -> header.arraytype = ARRAYTYPE_CHAR;
816 /* create new javastring */
817 js = LNEW (java_lang_String);
818 js -> header.vftbl = class_java_lang_String -> vftbl;
819 js -> value = stringdata;
821 js -> count = length;
823 /* create new literalstring */
824 s = NEW (literalstring);
825 s->hashlink = string_hash.ptr[slot];
826 s->string = (java_objectheader *) js;
827 string_hash.ptr[slot] = s;
829 /* update numbe of hashtable entries */
830 string_hash.entries++;
832 /* reorganization of hashtable */
833 if ( string_hash.entries > (string_hash.size*2)) {
835 /* reorganization of hashtable, average length of
836 the external chains is approx. 2 */
840 hashtable newhash; /* the new hashtable */
842 /* create new hashtable, double the size */
843 init_hashtable(&newhash, string_hash.size*2);
844 newhash.entries=string_hash.entries;
846 /* transfer elements to new hashtable */
847 for (i=0; i<string_hash.size; i++) {
848 s = string_hash.ptr[i];
850 literalstring *nexts = s -> hashlink;
851 js = (java_lang_String*) s->string;
852 slot = (unicode_hashkey(js->value->data,js->count)) & (newhash.size-1);
854 s->hashlink = newhash.ptr[slot];
855 newhash.ptr[slot] = s;
857 /* follow link in external hash chain */
862 /* dispose old table */
863 MFREE (string_hash.ptr, void*, string_hash.size);
864 string_hash = newhash;
867 return (java_objectheader *) js;
870 /******************** Function: literalstring_new *****************************
872 creates a new javastring with the text of the utf-symbol
873 and inserts it into the string hashtable
875 *******************************************************************************/
877 java_objectheader *literalstring_new (utf *u)
879 char *utf_ptr = u->text; /* pointer to current unicode character in utf string */
880 u4 utflength = utf_strlen(u); /* length of utf-string if uncompressed */
881 java_chararray *a; /* u2-array constructed from utf string */
882 java_objectheader *js;
885 /* allocate memory */
886 a = lit_mem_alloc (sizeof(java_chararray) + sizeof(u2)*(utflength-1)+10 );
887 /* convert utf-string to u2-array */
888 for (i=0; i<utflength; i++) a->data[i] = utf_nextu2(&utf_ptr);
890 return literalstring_u2(a, utflength, false);
894 /********************** function: literalstring_free **************************
896 removes a javastring from memory
898 ******************************************************************************/
900 void literalstring_free (java_objectheader* sobj)
902 java_lang_String *s = (java_lang_String*) sobj;
903 java_chararray *a = s->value;
905 log_text("literalstring_free called");
907 /* dispose memory of java.lang.String object */
908 LFREE (s, java_lang_String);
909 /* dispose memory of java-characterarray */
910 LFREE (a, sizeof(java_chararray) + sizeof(u2)*(a->header.size-1)); /* +10 ?? */