Merged everything with MIPS version
[cacao.git] / src / native / native.c
1 /****************************** native.c ***************************************
2
3         Copyright (c) 1997 A. Krall, R. Grafl, M. Gschwind, M. Probst
4
5         See file COPYRIGHT for information on usage and disclaimer of warranties
6
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.
10         
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 
14
15         Last Change: 1996/11/14
16
17 *******************************************************************************/
18
19 #include <unistd.h>
20 #include <time.h>
21 #include "global.h"
22 #include "native.h"
23 #include "nativetypes.hh"
24 #include "builtin.h"
25 #include "asmpart.h"
26 #include "tables.h"
27 #include "loader.h"
28 #include <math.h>
29 #include <string.h>
30 #include <assert.h>
31 #include <sys/time.h>
32 #include <utime.h>
33
34 #include "threads/thread.h"                       /* schani */
35 #include "threads/locks.h"
36
37 /* Include files for IO functions */
38
39 #include <fcntl.h>
40 #include <dirent.h>
41 #include <sys/types.h>
42 #ifdef _OSF_SOURCE 
43 #include <sys/mode.h>
44 #endif
45 #include <sys/stat.h>
46
47 #include "../threads/threadio.h"                    
48
49 /* searchpath for classfiles */
50 static char *classpath;
51
52 /* for java-string to char conversion */
53 #define MAXSTRINGSIZE 1000                          
54
55 /******************** systemclasses required for native methods ***************/
56
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;
86
87 /* the system classloader object */
88 struct java_lang_ClassLoader *SystemClassLoader = NULL;
89
90 /* for raising exceptions from native methods */
91 java_objectheader* exceptionptr = NULL;
92
93 /************* use classinfo structure as java.lang.Class object **************/
94
95 static void use_class_as_object (classinfo *c) 
96 {
97         c->header.vftbl = class_java_lang_Class -> vftbl;
98 }
99
100 /*********************** include Java Native Interface ************************/ 
101
102 #include "jni.c"
103
104 /*************************** include native methods ***************************/ 
105
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"
151
152 /************************** tables for methods ********************************/
153
154 /* table for locating native methods */
155 static struct nativeref {
156         char *classname;
157         char *methodname;
158         char *descriptor;
159         bool isstatic;
160         functionptr func;
161 } nativetable [] = {
162
163 #include "nativetable.hh"
164
165 };
166
167
168 #define NATIVETABLESIZE  (sizeof(nativetable)/sizeof(struct nativeref))
169
170 /* table for fast string comparison */
171 static struct nativecompref {
172         utf *classname;
173         utf *methodname;
174         utf *descriptor;
175         bool isstatic;
176         functionptr func;
177         } nativecomptable [NATIVETABLESIZE];
178
179 /* string comparsion table initialized */
180 static bool nativecompdone = false;
181
182
183 /*********************** function: native_loadclasses **************************
184
185         load classes required for native methods        
186
187 *******************************************************************************/
188
189 void native_loadclasses()
190 {
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") );      
232
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") );
252
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"));
257         
258         /* start classloader */
259         loader_load(utf_new_char("sun/io/ByteToCharISO8859_1")); 
260 }
261
262
263 /*************** adds a class to the vector of loaded classes ****************/
264
265 void systemclassloader_addclass(classinfo *c)
266 {
267         methodinfo *m;
268
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;)")
274             );
275
276         if (!m) panic("warning: cannot initialize classloader");
277
278         /* prepare class to be passed as argument */
279         use_class_as_object (c);
280
281         /* call 'addClass' */
282         asm_calljavamethod(m,
283                            (java_objectheader*) SystemClassLoader, 
284                            (java_objectheader*) c,
285                            NULL,  
286                            NULL
287                           );       
288 }
289
290 /*************** adds a library to the vector of loaded libraries *************/
291
292 void systemclassloader_addlibrary(java_objectheader *o)
293 {
294         methodinfo *m;
295
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")
301             );
302
303         if (!m) panic("cannot initialize classloader");
304
305         /* call 'addElement' */
306         asm_calljavamethod(m,
307                            SystemClassLoader->nativeLibraries,
308                            o,
309                            NULL,  
310                            NULL
311                           );       
312 }
313
314 /*****************************************************************************
315
316         create systemclassloader object and initialize instance fields  
317
318 ******************************************************************************/
319
320 void init_systemclassloader() 
321 {
322   if (!SystemClassLoader) {
323
324         /* create object and call initializer */
325         SystemClassLoader = (java_lang_ClassLoader*) native_new_and_init(class_java_lang_ClassLoader);  
326         heap_addreference((void**) &SystemClassLoader);
327
328         /* systemclassloader has no parent */
329         SystemClassLoader->parent      = NULL;
330         SystemClassLoader->initialized = true;
331   }
332 }
333
334
335 /********************* add loaded library name  *******************************/
336
337 void systemclassloader_addlibname(java_objectheader *o)
338 {
339         methodinfo *m;
340         java_objectheader *LibraryNameVector;
341         jfieldID id;
342
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")
347             );
348
349         if (!m) panic("cannot initialize classloader");
350
351         id = env.GetStaticFieldID(&env,class_java_lang_ClassLoader,"loadedLibraryNames","Ljava/util/Vector;");
352         if (!id) panic("can not access ClassLoader");
353
354         asm_calljavamethod(m,
355                            GetStaticObjectField(&env,class_java_lang_ClassLoader,id),
356                            o,
357                            NULL,  
358                            NULL
359                           );       
360 }
361
362
363 /********************* function: native_setclasspath **************************/
364  
365 void native_setclasspath (char *path)
366 {
367         /* set searchpath for classfiles */
368         classpath = path;
369 }
370
371 /***************** function: throw_classnotfoundexception *********************/
372
373 void throw_classnotfoundexception()
374 {
375         /* throws a ClassNotFoundException */
376         exceptionptr = native_new_and_init (class_java_lang_ClassNotFoundException);
377 }
378
379
380 /*********************** Function: native_findfunction *************************
381
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)
385
386         Remark: For faster operation, the names/descriptors are converted from C
387                 strings to Unicode the first time this function is called.
388
389 *******************************************************************************/
390
391 functionptr native_findfunction (utf *cname, utf *mname, 
392                                  utf *desc, bool isstatic)
393 {
394         int i;
395         /* entry of table for fast string comparison */
396         struct nativecompref *n;
397         /* for warning message if no function is found */
398         char *buffer;                   
399         int buffer_len, pos;
400
401         isstatic = isstatic ? true : false;
402
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       = 
414                                         nativetable[i].func;
415                         }
416                 nativecompdone = true;
417                 }
418
419         for (i = 0; i < NATIVETABLESIZE; i++) {
420                 n = &(nativecomptable[i]);
421
422                 if (cname == n->classname && mname == n->methodname &&
423                     desc == n->descriptor && isstatic == n->isstatic)
424                         return n->func;
425                 }
426
427         /* no function was found, display warning */
428
429         buffer_len = 
430           utf_strlen(cname) + utf_strlen(mname) + utf_strlen(desc) + 64;
431
432         buffer = MNEW(char, buffer_len);
433
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);
440
441         log_text(buffer);       
442
443         MFREE(buffer, char, buffer_len);
444
445         return NULL;
446 }
447
448
449 /********************** function: javastring_new *******************************
450
451         creates a new object of type java/lang/String with the text of 
452         the specified utf8-string
453
454         return: pointer to the string or NULL if memory is exhausted.   
455
456 *******************************************************************************/
457
458 java_objectheader *javastring_new (utf *u)
459 {
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                          */
463         java_chararray *a;
464         s4 i;
465         
466         s = (java_lang_String*) builtin_new (class_java_lang_String);
467         a = builtin_newarray_char (utflength);
468
469         /* javastring or character-array could not be created */
470         if ((!a) || (!s))
471                 return NULL;
472
473         /* decompress utf-string */
474         for (i = 0; i < utflength; i++)
475                 a->data[i] = utf_nextu2(&utf_ptr);
476         
477         /* set fields of the javastring-object */
478         s -> value  = a;
479         s -> offset = 0;
480         s -> count  = utflength;
481
482         return (java_objectheader*) s;
483 }
484
485 /********************** function: javastring_new_char **************************
486
487         creates a new java/lang/String object which contains the convertet
488         C-string passed via text.
489
490         return: the object pointer or NULL if memory is exhausted.
491
492 *******************************************************************************/
493
494 java_objectheader *javastring_new_char (char *text)
495 {
496         s4 i;
497         s4 len = strlen(text); /* length of the string */
498         java_lang_String *s;   /* result-string */
499         java_chararray *a;
500         
501         s = (java_lang_String*) builtin_new (class_java_lang_String);
502         a = builtin_newarray_char (len);
503
504         /* javastring or character-array could not be created */
505         if ((!a) || (!s)) return NULL;
506
507         /* copy text */
508         for (i = 0; i < len; i++)
509                 a->data[i] = text[i];
510         
511         /* set fields of the javastring-object */
512         s -> value = a;
513         s -> offset = 0;
514         s -> count = len;
515
516         return (java_objectheader*) s;
517 }
518
519
520 /************************* function javastring_tochar **************************
521
522         converts a Java string into a C string.
523         
524         return: pointer to C string
525         
526         Caution: every call of this function overwrites the previous string !!!
527         
528 *******************************************************************************/
529
530 static char stringbuffer[MAXSTRINGSIZE];
531
532 char *javastring_tochar (java_objectheader *so) 
533 {
534         java_lang_String *s = (java_lang_String*) so;
535         java_chararray *a;
536         s4 i;
537         
538         if (!s)
539                 return "";
540         a = s->value;
541         if (!a)
542                 return "";
543         if (s->count > MAXSTRINGSIZE)
544                 return "";
545         for (i = 0; i < s->count; i++)
546                 stringbuffer[i] = a->data[s->offset+i];
547         stringbuffer[i] = '\0';
548         return stringbuffer;
549 }
550
551
552 /****************** function class_findfield_approx ****************************
553         
554         searches in 'classinfo'-structure for a field with the
555         specified name
556
557 *******************************************************************************/
558  
559 fieldinfo *class_findfield_approx (classinfo *c, utf *name)
560 {
561         s4 i;
562         for (i = 0; i < c->fieldscount; i++) {
563                 /* compare field names */
564                 if ((c->fields[i].name == name))
565                         return &(c->fields[i]);
566                 }
567
568         /* field was not found, raise exception */      
569         exceptionptr = native_new_and_init(class_java_lang_NoSuchFieldException);
570         return NULL;
571 }
572
573
574 /********************** function: native_new_and_init *************************
575
576         Creates a new object on the heap and calls the initializer.
577         Returns the object pointer or NULL if memory is exhausted.
578                         
579 *******************************************************************************/
580
581 java_objectheader *native_new_and_init (classinfo *c)
582 {
583         methodinfo *m;
584         java_objectheader *o = builtin_new (c);         /*          create object */
585
586         if (!o) return NULL;
587         
588         /* find initializer */
589
590         m = class_findmethod(c, utf_new_char("<init>"), utf_new_char("()V"));
591                                                       
592         if (!m) {                                       /* initializer not found  */
593                 if (verbose) {
594                         sprintf(logtext, "Warning: class has no instance-initializer: ");
595                         utf_sprint(logtext + strlen(logtext), c->name);
596                         dolog();
597                         }
598                 return o;
599                 }
600
601         /* call initializer */
602
603         asm_calljavamethod (m, o, NULL, NULL, NULL);
604         return o;
605 }
606
607 /******************** function: stringtable_update ****************************
608
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
612
613 *******************************************************************************/
614  
615 void stringtable_update ()
616 {
617         java_lang_String *js;   
618         java_chararray *a;
619         literalstring *s;       /* hashtable entry */
620         int i;
621
622         for (i = 0; i < string_hash.size; i++) {
623                 s = string_hash.ptr[i];
624                 if (s) {
625                         while (s) {
626                                                                 
627                                 js = (java_lang_String *) s->string;
628                                 
629                                 if (!js || !(a = js->value)) 
630                                         /* error in hashtable found */
631                                         panic("invalid literalstring in hashtable");
632
633                                 if (!js->header.vftbl) 
634                                         /* vftbl of javastring is NULL */ 
635                                         js->header.vftbl = class_java_lang_String -> vftbl;
636
637                                 if (!a->header.objheader.vftbl) 
638                                         /* vftbl of character-array is NULL */ 
639                                         a->header.objheader.vftbl = class_array -> vftbl;
640
641                                 /* follow link in external hash chain */
642                                 s = s->hashlink;
643                         }       
644                 }               
645         }
646 }
647
648
649 /************************* function: u2_utflength ***************************
650
651         returns the utf length in bytes of a u2 array 
652
653 *****************************************************************************/
654
655
656 u4 u2_utflength(u2 *text, u4 u2_length)
657 {
658         u4 result_len =  0;  /* utf length in bytes  */
659         u2 ch;               /* current unicode character */
660         u4 len;
661         
662         for (len = 0; len < u2_length; len++) {
663           
664           /* next unicode character */
665           ch = *text++;
666           
667           /* determine bytes required to store unicode character as utf */
668           if (ch && (ch < 0x80)) 
669             result_len++;
670           else if (ch < 0x800)
671             result_len += 2;    
672           else 
673             result_len += 3;    
674         }
675
676     return result_len;
677 }
678
679 /********************* function: utf_new_u2 ***********************************
680
681         make utf symbol from u2 array, 
682         if isclassname is true '.' is replaced by '/'
683
684 *******************************************************************************/
685
686 utf *utf_new_u2(u2 *unicode_pos, u4 unicode_length, bool isclassname)
687 {
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 */
693         int i;          
694
695         /* determine utf length in bytes and allocate memory */         
696         buflength = u2_utflength(unicode_pos, unicode_length); 
697         buffer    = MNEW(char,buflength);
698  
699         /* memory allocation failed */
700         if (!buffer) return NULL;
701
702         left = buflength;
703         pos  = buffer;
704
705         for (i = 0; i++ < unicode_length; unicode_pos++) {
706                 /* next unicode character */
707                 u2 c = *unicode_pos;
708                 
709                 if ((c != 0) && (c < 0x80)) {
710                 /* 1 character */       
711                 left--;
712                 if ((int) left < 0) break;
713                 /* convert classname */
714                 if (isclassname && c=='.') 
715                   *pos++ = '/';
716                 else
717                   *pos++ = (char) c;
718                 } else if (c < 0x800) {             
719                 /* 2 characters */                              
720                 unsigned char high = c >> 6;
721                 unsigned char low  = c & 0x3F;
722                 left = left - 2;
723                 if ((int) left < 0) break;
724                 *pos++ = high | 0xC0; 
725                 *pos++ = low  | 0x80;     
726                 } else {         
727                 /* 3 characters */                              
728                 char low  = c & 0x3f;
729                 char mid  = (c >> 6) & 0x3F;
730                 char high = c >> 12;
731                 left = left - 3;
732                 if ((int) left < 0) break;
733                 *pos++ = high | 0xE0; 
734                 *pos++ = mid  | 0x80;  
735                 *pos++ = low  | 0x80;   
736                 }
737         }
738         
739         /* insert utf-string into symbol-table */
740         result = utf_new(buffer,buflength);
741         MFREE(buffer, char, buflength);
742         return result;
743 }
744
745 /********************* function: javastring_toutf *****************************
746
747         make utf symbol from javastring
748
749 *******************************************************************************/
750
751 utf *javastring_toutf(java_lang_String *string, bool isclassname)
752 {
753         java_lang_String *str = (java_lang_String *) string;
754         return utf_new_u2(str->value->data,str->count, isclassname);
755 }
756
757 /********************* function: literalstring_u2 *****************************
758
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 
761     created 
762
763     if copymode is true a copy of the u2-array is made
764
765 *******************************************************************************/
766
767 java_objectheader *literalstring_u2 (java_chararray *a, u4 length, bool copymode )
768 {
769     literalstring *s;                /* hashtable element */
770     java_lang_String *js;            /* u2-array wrapped in javastring */
771     java_chararray *stringdata;      /* copy of u2-array */      
772     u4 key;   
773     u4 slot;  
774     u2 i;
775
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];
780
781     while (s) {
782         
783       js = (java_lang_String *) s->string;
784         
785       if (js->count == length) {
786         /* compare text */
787         for (i=0; i<length; i++) 
788           if (js->value->data[i] != a->data[i]) goto nomatch;
789                                         
790         /* string already in hashtable, free memory */
791         if (!copymode)
792           lit_mem_free(a, sizeof(java_chararray) + sizeof(u2)*(length-1)+10);
793
794         return (java_objectheader *) js;
795       }
796
797       nomatch:
798       /* follow link in external hash chain */
799       s = s->hashlink;
800     }
801
802     if (copymode) {
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 );        
807     }  
808     else
809       stringdata = a;
810
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;    
816
817     /* create new javastring */
818     js = LNEW (java_lang_String);
819     js -> header.vftbl = class_java_lang_String -> vftbl;
820     js -> value  = stringdata;
821     js -> offset = 0;
822     js -> count  = length;
823
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;
829
830     /* update numbe of hashtable entries */
831     string_hash.entries++;
832
833     /* reorganization of hashtable */       
834     if ( string_hash.entries > (string_hash.size*2)) {
835
836       /* reorganization of hashtable, average length of 
837          the external chains is approx. 2                */  
838
839       u4 i;
840       literalstring *s;     
841       hashtable newhash; /* the new hashtable */
842       
843       /* create new hashtable, double the size */
844       init_hashtable(&newhash, string_hash.size*2);
845       newhash.entries=string_hash.entries;
846       
847       /* transfer elements to new hashtable */
848       for (i=0; i<string_hash.size; i++) {
849         s = string_hash.ptr[i];
850         while (s) {
851           literalstring *nexts = s -> hashlink;  
852           js   = (java_lang_String*) s->string;
853           slot = (unicode_hashkey(js->value->data,js->count)) & (newhash.size-1);
854           
855           s->hashlink = newhash.ptr[slot];
856           newhash.ptr[slot] = s;
857         
858           /* follow link in external hash chain */  
859           s = nexts;
860         }
861       }
862         
863       /* dispose old table */   
864       MFREE (string_hash.ptr, void*, string_hash.size);
865       string_hash = newhash;
866     }
867                         
868     return (java_objectheader *) js;
869 }
870
871 /******************** Function: literalstring_new *****************************
872
873     creates a new javastring with the text of the utf-symbol
874     and inserts it into the string hashtable
875
876 *******************************************************************************/
877
878 java_objectheader *literalstring_new (utf *u)
879 {
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;
884     u4 i;
885     
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);      
890
891     return literalstring_u2(a, utflength, false);
892 }
893
894
895 /********************** function: literalstring_free **************************
896
897         removes a javastring from memory                       
898
899 ******************************************************************************/
900
901 void literalstring_free (java_objectheader* sobj)
902 {
903         java_lang_String *s = (java_lang_String*) sobj;
904         java_chararray *a = s->value;
905
906         log_text("literalstring_free called");
907         
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 ?? */
912 }
913
914
915
916
917
918