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"
34 #include "threads/thread.h" /* schani */
35 #include "threads/locks.h"
37 /* Include files for IO functions */
41 #include <sys/types.h>
47 #include "../threads/threadio.h"
49 /* searchpath for classfiles */
50 static char *classpath;
52 /* for java-string to char conversion */
53 #define MAXSTRINGSIZE 1000
55 /******************** systemclasses required for native methods ***************/
57 static classinfo *class_java_lang_Class;
58 static classinfo *class_java_lang_Cloneable;
59 static classinfo *class_java_lang_CloneNotSupportedException;
60 static classinfo *class_java_lang_System;
61 static classinfo *class_java_lang_ClassLoader;
62 static classinfo *class_java_lang_ClassNotFoundException;
63 static classinfo *class_java_lang_InstantiationException;
64 static classinfo *class_java_lang_NoSuchMethodError;
65 static classinfo *class_java_lang_NoSuchFieldError;
66 static classinfo *class_java_lang_ClassFormatError;
67 static classinfo *class_java_lang_IllegalArgumentException;
68 static classinfo *class_java_lang_ArrayIndexOutOfBoundsException;
69 static classinfo *class_java_lang_NoSuchFieldException;
70 static classinfo *class_java_io_SyncFailedException;
71 static classinfo *class_java_io_IOException;
72 static classinfo *class_java_io_UnixFileSystem;
73 static classinfo *class_java_security_PrivilegedActionException;
74 static classinfo *class_java_net_UnknownHostException;
75 static classinfo *class_java_net_SocketException;
76 static classinfo *class_java_lang_NoSuchMethodException;
77 static classinfo *class_java_lang_Double;
78 static classinfo *class_java_lang_Float;
79 static classinfo *class_java_lang_Long;
80 static classinfo *class_java_lang_Byte;
81 static classinfo *class_java_lang_Short;
82 static classinfo *class_java_lang_Boolean;
83 static classinfo *class_java_lang_Void;
84 static classinfo *class_java_lang_Character;
85 static classinfo *class_java_lang_Integer;
87 /* the system classloader object */
88 struct java_lang_ClassLoader *SystemClassLoader = NULL;
90 /* for raising exceptions from native methods */
91 java_objectheader* exceptionptr = NULL;
93 /************* use classinfo structure as java.lang.Class object **************/
95 static void use_class_as_object (classinfo *c)
97 c->header.vftbl = class_java_lang_Class -> vftbl;
100 /*********************** include Java Native Interface ************************/
104 /*************************** include native methods ***************************/
106 #include "nat/Object.c"
107 #include "nat/String.c"
108 #include "nat/ClassLoader.c"
109 #include "nat/Class.c"
110 #include "nat/Compiler.c"
111 #include "nat/Double.c"
112 #include "nat/Float.c"
113 #include "nat/Math.c"
114 #include "nat/Package.c"
115 #include "nat/Runtime.c"
116 #include "nat/SecurityManager.c"
117 #include "nat/System.c"
118 #include "nat/Thread.c"
119 #include "nat/Throwable.c"
120 #include "nat/Finalizer.c"
121 #include "nat/Array.c"
122 #include "nat/Constructor.c"
123 #include "nat/Field.c"
124 #include "nat/Method.c"
125 #include "nat/FileDescriptor.c"
126 #include "nat/FileInputStream.c"
127 #include "nat/FileOutputStream.c"
128 #include "nat/FileSystem.c"
129 #include "nat/ObjectInputStream.c"
130 #include "nat/ObjectStreamClass.c"
131 #include "nat/RandomAccessFile.c"
132 #include "nat/ResourceBundle.c"
133 #include "nat/JarFile.c"
134 #include "nat/Adler32.c"
135 #include "nat/CRC32.c"
136 #include "nat/Deflater.c"
137 #include "nat/Inflater.c"
138 #include "nat/ZipEntry.c"
139 #include "nat/ZipFile.c"
140 #include "nat/BigInteger.c"
141 #include "nat/InetAddress.c"
142 #include "nat/InetAddressImpl.c"
143 #include "nat/DatagramPacket.c"
144 #include "nat/PlainDatagramSocketImpl.c"
145 #include "nat/PlainSocketImpl.c"
146 #include "nat/SocketInputStream.c"
147 #include "nat/SocketOutputStream.c"
148 #include "nat/AccessController.c"
149 #include "nat/ClassLoader_NativeLibrary.c"
150 #include "nat/UnixFileSystem.c"
152 /************************** tables for methods ********************************/
154 /* table for locating native methods */
155 static struct nativeref {
163 #include "nativetable.hh"
168 #define NATIVETABLESIZE (sizeof(nativetable)/sizeof(struct nativeref))
170 /* table for fast string comparison */
171 static struct nativecompref {
177 } nativecomptable [NATIVETABLESIZE];
179 /* string comparsion table initialized */
180 static bool nativecompdone = false;
183 /*********************** function: native_loadclasses **************************
185 load classes required for native methods
187 *******************************************************************************/
189 void native_loadclasses()
191 /* class_new adds the class to the list of classes to be loaded */
192 class_java_lang_Cloneable =
193 class_new ( utf_new_char ("java/lang/Cloneable") );
194 class_java_lang_CloneNotSupportedException =
195 class_new ( utf_new_char ("java/lang/CloneNotSupportedException") );
196 class_java_lang_Class =
197 class_new ( utf_new_char ("java/lang/Class") );
198 class_java_io_IOException =
199 class_new ( utf_new_char ("java/io/IOException") );
200 class_java_lang_ClassNotFoundException =
201 class_new ( utf_new_char ("java/lang/ClassNotFoundException") );
202 class_java_lang_InstantiationException =
203 class_new ( utf_new_char ("java/lang/InstantiationException") );
204 class_java_lang_NoSuchMethodError =
205 class_new ( utf_new_char ("java/lang/NoSuchMethodError") );
206 class_java_lang_NoSuchFieldError =
207 class_new ( utf_new_char ("java/lang/NoSuchFieldError") );
208 class_java_lang_ClassFormatError =
209 class_new ( utf_new_char ("java/lang/ClassFormatError") );
210 class_java_io_SyncFailedException =
211 class_new ( utf_new_char ("java/io/SyncFailedException") );
212 class_java_io_UnixFileSystem =
213 class_new ( utf_new_char ("java/io/UnixFileSystem") );
214 class_java_lang_System =
215 class_new ( utf_new_char ("java/lang/System") );
216 class_java_lang_ClassLoader =
217 class_new ( utf_new_char ("java/lang/ClassLoader") );
218 class_java_security_PrivilegedActionException =
219 class_new( utf_new_char("java/security/PrivilegedActionException"));
220 class_java_net_UnknownHostException =
221 loader_load( utf_new_char ("java/net/UnknownHostException") );
222 class_java_net_SocketException =
223 loader_load( utf_new_char ("java/net/SocketException") );
224 class_java_lang_IllegalArgumentException =
225 class_new( utf_new_char("java/lang/IllegalArgumentException"));
226 class_java_lang_ArrayIndexOutOfBoundsException =
227 class_new( utf_new_char ("java/lang/ArrayIndexOutOfBoundsException") );
228 class_java_lang_NoSuchFieldException =
229 class_new( utf_new_char ("java/lang/NoSuchFieldException") );
230 class_java_lang_NoSuchMethodException =
231 class_new( utf_new_char ("java/lang/NoSuchMethodException") );
233 /* load classes for wrapping primitive types */
234 class_java_lang_Double =
235 class_new( utf_new_char ("java/lang/Double") );
236 class_java_lang_Float =
237 class_new( utf_new_char ("java/lang/Float") );
238 class_java_lang_Character =
239 class_new( utf_new_char ("java/lang/Character") );
240 class_java_lang_Integer =
241 class_new( utf_new_char ("java/lang/Integer") );
242 class_java_lang_Long =
243 class_new( utf_new_char ("java/lang/Long") );
244 class_java_lang_Byte =
245 class_new( utf_new_char ("java/lang/Byte") );
246 class_java_lang_Short =
247 class_new( utf_new_char ("java/lang/Short") );
248 class_java_lang_Boolean =
249 class_new( utf_new_char ("java/lang/Boolean") );
250 class_java_lang_Void =
251 class_new( utf_new_char ("java/lang/Void") );
253 /* load to avoid dynamic classloading */
254 class_new(utf_new_char("sun/net/www/protocol/file/Handler"));
255 class_new(utf_new_char("sun/net/www/protocol/jar/Handler"));
256 class_new(utf_new_char("sun/io/CharToByteISO8859_1"));
258 /* start classloader */
259 loader_load(utf_new_char("sun/io/ByteToCharISO8859_1"));
263 /*************** adds a class to the vector of loaded classes ****************/
265 void systemclassloader_addclass(classinfo *c)
269 /* find method addClass of java.lang.ClassLoader */
270 m = class_resolvemethod (
271 class_java_lang_ClassLoader,
272 utf_new_char("addClass"),
273 utf_new_char("(Ljava/lang/Class;)")
276 if (!m) panic("warning: cannot initialize classloader");
278 /* prepare class to be passed as argument */
279 use_class_as_object (c);
281 /* call 'addClass' */
282 asm_calljavamethod(m,
283 (java_objectheader*) SystemClassLoader,
284 (java_objectheader*) c,
290 /*************** adds a library to the vector of loaded libraries *************/
292 void systemclassloader_addlibrary(java_objectheader *o)
296 /* find method addElement of java.util.Vector */
297 m = class_resolvemethod (
298 loader_load ( utf_new_char ("java/util/Vector") ),
299 utf_new_char("addElement"),
300 utf_new_char("(Ljava/lang/Object;)V")
303 if (!m) panic("cannot initialize classloader");
305 /* call 'addElement' */
306 asm_calljavamethod(m,
307 SystemClassLoader->nativeLibraries,
314 /*****************************************************************************
316 create systemclassloader object and initialize instance fields
318 ******************************************************************************/
320 void init_systemclassloader()
322 if (!SystemClassLoader) {
324 /* create object and call initializer */
325 SystemClassLoader = (java_lang_ClassLoader*) native_new_and_init(class_java_lang_ClassLoader);
326 heap_addreference((void**) &SystemClassLoader);
328 /* systemclassloader has no parent */
329 SystemClassLoader->parent = NULL;
330 SystemClassLoader->initialized = true;
335 /********************* add loaded library name *******************************/
337 void systemclassloader_addlibname(java_objectheader *o)
340 java_objectheader *LibraryNameVector;
343 m = class_resolvemethod (
344 loader_load ( utf_new_char ("java/util/Vector") ),
345 utf_new_char("addElement"),
346 utf_new_char("(Ljava/lang/Object;)V")
349 if (!m) panic("cannot initialize classloader");
351 id = env.GetStaticFieldID(&env,class_java_lang_ClassLoader,"loadedLibraryNames","Ljava/util/Vector;");
352 if (!id) panic("can not access ClassLoader");
354 asm_calljavamethod(m,
355 GetStaticObjectField(&env,class_java_lang_ClassLoader,id),
363 /********************* function: native_setclasspath **************************/
365 void native_setclasspath (char *path)
367 /* set searchpath for classfiles */
371 /***************** function: throw_classnotfoundexception *********************/
373 void throw_classnotfoundexception()
375 /* throws a ClassNotFoundException */
376 exceptionptr = native_new_and_init (class_java_lang_ClassNotFoundException);
380 /*********************** Function: native_findfunction *************************
382 Looks up a method (must have the same class name, method name, descriptor
383 and 'static'ness) and returns a function pointer to it.
384 Returns: function pointer or NULL (if there is no such method)
386 Remark: For faster operation, the names/descriptors are converted from C
387 strings to Unicode the first time this function is called.
389 *******************************************************************************/
391 functionptr native_findfunction (utf *cname, utf *mname,
392 utf *desc, bool isstatic)
395 /* entry of table for fast string comparison */
396 struct nativecompref *n;
397 /* for warning message if no function is found */
401 isstatic = isstatic ? true : false;
403 if (!nativecompdone) {
404 for (i = 0; i < NATIVETABLESIZE; i++) {
405 nativecomptable[i].classname =
406 utf_new_char(nativetable[i].classname);
407 nativecomptable[i].methodname =
408 utf_new_char(nativetable[i].methodname);
409 nativecomptable[i].descriptor =
410 utf_new_char(nativetable[i].descriptor);
411 nativecomptable[i].isstatic =
412 nativetable[i].isstatic;
413 nativecomptable[i].func =
416 nativecompdone = true;
419 for (i = 0; i < NATIVETABLESIZE; i++) {
420 n = &(nativecomptable[i]);
422 if (cname == n->classname && mname == n->methodname &&
423 desc == n->descriptor && isstatic == n->isstatic)
427 /* no function was found, display warning */
430 utf_strlen(cname) + utf_strlen(mname) + utf_strlen(desc) + 64;
432 buffer = MNEW(char, buffer_len);
434 strcpy(buffer, "warning: native function ");
435 utf_sprint(buffer+strlen(buffer), mname);
436 strcpy(buffer+strlen(buffer), ": ");
437 utf_sprint(buffer+strlen(buffer), desc);
438 strcpy(buffer+strlen(buffer), " not found in class ");
439 utf_sprint(buffer+strlen(buffer), cname);
443 MFREE(buffer, char, buffer_len);
449 /********************** function: javastring_new *******************************
451 creates a new object of type java/lang/String with the text of
452 the specified utf8-string
454 return: pointer to the string or NULL if memory is exhausted.
456 *******************************************************************************/
458 java_objectheader *javastring_new (utf *u)
460 char *utf_ptr = u->text; /* current utf character in utf string */
461 int utflength = utf_strlen(u); /* length of utf-string if uncompressed */
462 java_lang_String *s; /* result-string */
466 s = (java_lang_String*) builtin_new (class_java_lang_String);
467 a = builtin_newarray_char (utflength);
469 /* javastring or character-array could not be created */
473 /* decompress utf-string */
474 for (i = 0; i < utflength; i++)
475 a->data[i] = utf_nextu2(&utf_ptr);
477 /* set fields of the javastring-object */
480 s -> count = utflength;
482 return (java_objectheader*) s;
485 /********************** function: javastring_new_char **************************
487 creates a new java/lang/String object which contains the convertet
488 C-string passed via text.
490 return: the object pointer or NULL if memory is exhausted.
492 *******************************************************************************/
494 java_objectheader *javastring_new_char (char *text)
497 s4 len = strlen(text); /* length of the string */
498 java_lang_String *s; /* result-string */
501 s = (java_lang_String*) builtin_new (class_java_lang_String);
502 a = builtin_newarray_char (len);
504 /* javastring or character-array could not be created */
505 if ((!a) || (!s)) return NULL;
508 for (i = 0; i < len; i++)
509 a->data[i] = text[i];
511 /* set fields of the javastring-object */
516 return (java_objectheader*) s;
520 /************************* function javastring_tochar **************************
522 converts a Java string into a C string.
524 return: pointer to C string
526 Caution: every call of this function overwrites the previous string !!!
528 *******************************************************************************/
530 static char stringbuffer[MAXSTRINGSIZE];
532 char *javastring_tochar (java_objectheader *so)
534 java_lang_String *s = (java_lang_String*) so;
543 if (s->count > MAXSTRINGSIZE)
545 for (i = 0; i < s->count; i++)
546 stringbuffer[i] = a->data[s->offset+i];
547 stringbuffer[i] = '\0';
552 /****************** function class_findfield_approx ****************************
554 searches in 'classinfo'-structure for a field with the
557 *******************************************************************************/
559 fieldinfo *class_findfield_approx (classinfo *c, utf *name)
562 for (i = 0; i < c->fieldscount; i++) {
563 /* compare field names */
564 if ((c->fields[i].name == name))
565 return &(c->fields[i]);
568 /* field was not found, raise exception */
569 exceptionptr = native_new_and_init(class_java_lang_NoSuchFieldException);
574 /********************** function: native_new_and_init *************************
576 Creates a new object on the heap and calls the initializer.
577 Returns the object pointer or NULL if memory is exhausted.
579 *******************************************************************************/
581 java_objectheader *native_new_and_init (classinfo *c)
584 java_objectheader *o = builtin_new (c); /* create object */
588 /* find initializer */
590 m = class_findmethod(c, utf_new_char("<init>"), utf_new_char("()V"));
592 if (!m) { /* initializer not found */
594 sprintf(logtext, "Warning: class has no instance-initializer: ");
595 utf_sprint(logtext + strlen(logtext), c->name);
601 /* call initializer */
603 asm_calljavamethod (m, o, NULL, NULL, NULL);
607 /******************** function: stringtable_update ****************************
609 traverses the javastring hashtable and sets the vftbl-entries of
610 javastrings which were temporarily set to NULL, because
611 java.lang.Object was not yet loaded
613 *******************************************************************************/
615 void stringtable_update ()
617 java_lang_String *js;
619 literalstring *s; /* hashtable entry */
622 for (i = 0; i < string_hash.size; i++) {
623 s = string_hash.ptr[i];
627 js = (java_lang_String *) s->string;
629 if (!js || !(a = js->value))
630 /* error in hashtable found */
631 panic("invalid literalstring in hashtable");
633 if (!js->header.vftbl)
634 /* vftbl of javastring is NULL */
635 js->header.vftbl = class_java_lang_String -> vftbl;
637 if (!a->header.objheader.vftbl)
638 /* vftbl of character-array is NULL */
639 a->header.objheader.vftbl = class_array -> vftbl;
641 /* follow link in external hash chain */
649 /************************* function: u2_utflength ***************************
651 returns the utf length in bytes of a u2 array
653 *****************************************************************************/
656 u4 u2_utflength(u2 *text, u4 u2_length)
658 u4 result_len = 0; /* utf length in bytes */
659 u2 ch; /* current unicode character */
662 for (len = 0; len < u2_length; len++) {
664 /* next unicode character */
667 /* determine bytes required to store unicode character as utf */
668 if (ch && (ch < 0x80))
679 /********************* function: utf_new_u2 ***********************************
681 make utf symbol from u2 array,
682 if isclassname is true '.' is replaced by '/'
684 *******************************************************************************/
686 utf *utf_new_u2(u2 *unicode_pos, u4 unicode_length, bool isclassname)
688 char *buffer; /* memory buffer for unicode characters */
689 char *pos; /* pointer to current position in buffer */
690 u4 left; /* unicode characters left */
691 u4 buflength; /* utf length in bytes of the u2 array */
692 utf *result; /* resulting utf-string */
695 /* determine utf length in bytes and allocate memory */
696 buflength = u2_utflength(unicode_pos, unicode_length);
697 buffer = MNEW(char,buflength);
699 /* memory allocation failed */
700 if (!buffer) return NULL;
705 for (i = 0; i++ < unicode_length; unicode_pos++) {
706 /* next unicode character */
709 if ((c != 0) && (c < 0x80)) {
712 if ((int) left < 0) break;
713 /* convert classname */
714 if (isclassname && c=='.')
718 } else if (c < 0x800) {
720 unsigned char high = c >> 6;
721 unsigned char low = c & 0x3F;
723 if ((int) left < 0) break;
724 *pos++ = high | 0xC0;
729 char mid = (c >> 6) & 0x3F;
732 if ((int) left < 0) break;
733 *pos++ = high | 0xE0;
739 /* insert utf-string into symbol-table */
740 result = utf_new(buffer,buflength);
741 MFREE(buffer, char, buflength);
745 /********************* function: javastring_toutf *****************************
747 make utf symbol from javastring
749 *******************************************************************************/
751 utf *javastring_toutf(java_lang_String *string, bool isclassname)
753 java_lang_String *str = (java_lang_String *) string;
754 return utf_new_u2(str->value->data,str->count, isclassname);
757 /********************* function: literalstring_u2 *****************************
759 searches for the javastring with the specified u2-array in
760 the string hashtable, if there is no such string a new one is
763 if copymode is true a copy of the u2-array is made
765 *******************************************************************************/
767 java_objectheader *literalstring_u2 (java_chararray *a, u4 length, bool copymode )
769 literalstring *s; /* hashtable element */
770 java_lang_String *js; /* u2-array wrapped in javastring */
771 java_chararray *stringdata; /* copy of u2-array */
776 /* find location in hashtable */
777 key = unicode_hashkey (a->data, length);
778 slot = key & (string_hash.size-1);
779 s = string_hash.ptr[slot];
783 js = (java_lang_String *) s->string;
785 if (js->count == length) {
787 for (i=0; i<length; i++)
788 if (js->value->data[i] != a->data[i]) goto nomatch;
790 /* string already in hashtable, free memory */
792 lit_mem_free(a, sizeof(java_chararray) + sizeof(u2)*(length-1)+10);
794 return (java_objectheader *) js;
798 /* follow link in external hash chain */
803 /* create copy of u2-array for new javastring */
804 u4 arraysize = sizeof(java_chararray) + sizeof(u2)*(length-1)+10;
805 stringdata = lit_mem_alloc ( arraysize );
806 memcpy(stringdata, a, arraysize );
811 /* location in hashtable found, complete arrayheader */
812 if (class_array==NULL) panic("class_array not initialized");
813 stringdata -> header.objheader.vftbl = class_array -> vftbl;
814 stringdata -> header.size = length;
815 stringdata -> header.arraytype = ARRAYTYPE_CHAR;
817 /* create new javastring */
818 js = LNEW (java_lang_String);
819 js -> header.vftbl = class_java_lang_String -> vftbl;
820 js -> value = stringdata;
822 js -> count = length;
824 /* create new literalstring */
825 s = NEW (literalstring);
826 s->hashlink = string_hash.ptr[slot];
827 s->string = (java_objectheader *) js;
828 string_hash.ptr[slot] = s;
830 /* update numbe of hashtable entries */
831 string_hash.entries++;
833 /* reorganization of hashtable */
834 if ( string_hash.entries > (string_hash.size*2)) {
836 /* reorganization of hashtable, average length of
837 the external chains is approx. 2 */
841 hashtable newhash; /* the new hashtable */
843 /* create new hashtable, double the size */
844 init_hashtable(&newhash, string_hash.size*2);
845 newhash.entries=string_hash.entries;
847 /* transfer elements to new hashtable */
848 for (i=0; i<string_hash.size; i++) {
849 s = string_hash.ptr[i];
851 literalstring *nexts = s -> hashlink;
852 js = (java_lang_String*) s->string;
853 slot = (unicode_hashkey(js->value->data,js->count)) & (newhash.size-1);
855 s->hashlink = newhash.ptr[slot];
856 newhash.ptr[slot] = s;
858 /* follow link in external hash chain */
863 /* dispose old table */
864 MFREE (string_hash.ptr, void*, string_hash.size);
865 string_hash = newhash;
868 return (java_objectheader *) js;
871 /******************** Function: literalstring_new *****************************
873 creates a new javastring with the text of the utf-symbol
874 and inserts it into the string hashtable
876 *******************************************************************************/
878 java_objectheader *literalstring_new (utf *u)
880 char *utf_ptr = u->text; /* pointer to current unicode character in utf string */
881 u4 utflength = utf_strlen(u); /* length of utf-string if uncompressed */
882 java_chararray *a; /* u2-array constructed from utf string */
883 java_objectheader *js;
886 /* allocate memory */
887 a = lit_mem_alloc (sizeof(java_chararray) + sizeof(u2)*(utflength-1)+10 );
888 /* convert utf-string to u2-array */
889 for (i=0; i<utflength; i++) a->data[i] = utf_nextu2(&utf_ptr);
891 return literalstring_u2(a, utflength, false);
895 /********************** function: literalstring_free **************************
897 removes a javastring from memory
899 ******************************************************************************/
901 void literalstring_free (java_objectheader* sobj)
903 java_lang_String *s = (java_lang_String*) sobj;
904 java_chararray *a = s->value;
906 log_text("literalstring_free called");
908 /* dispose memory of java.lang.String object */
909 LFREE (s, java_lang_String);
910 /* dispose memory of java-characterarray */
911 LFREE (a, sizeof(java_chararray) + sizeof(u2)*(a->header.size-1)); /* +10 ?? */