native threads - checkcast fixes
[cacao.git] / headers.c
1 /* headers.c - main for header generation (cacaoh)
2
3    Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003
4    R. Grafl, A. Krall, C. Kruegel, C. Oates, R. Obermaisser,
5    M. Probst, S. Ring, E. Steiner, C. Thalinger, D. Thuernbeck,
6    P. Tomsich, J. Wenninger
7
8    This file is part of CACAO.
9
10    This program is free software; you can redistribute it and/or
11    modify it under the terms of the GNU General Public License as
12    published by the Free Software Foundation; either version 2, or (at
13    your option) any later version.
14
15    This program is distributed in the hope that it will be useful, but
16    WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18    General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with this program; if not, write to the Free Software
22    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
23    02111-1307, USA.
24
25    Contact: cacao@complang.tuwien.ac.at
26
27    Authors: Reinhard Grafl
28
29    Changes: Mark Probst
30             Philipp Tomsich
31
32    $Id: headers.c 1029 2004-04-26 15:56:34Z twisti $
33
34 */
35
36
37 #include <stdlib.h>
38 #include <string.h>
39 #include <ctype.h>
40 #include "config.h"
41 #include "global.h"
42 #include "tables.h"
43 #include "loader.h"
44 #include "builtin.h"
45 #include "mm/boehm.h"
46 #include "toolbox/chain.h"
47 #include "toolbox/memory.h"
48 #include "toolbox/loging.h"
49 #include "nat/java_lang_String.h"
50
51
52 /* replace command line options */
53
54 bool verbose =  false;
55 bool verboseexception =  false;
56 bool compileall = false;
57 bool runverbose = false;
58 bool collectverbose = false;
59
60 bool loadverbose = false;
61 bool linkverbose = false;
62 bool initverbose = false;
63
64 bool opt_rt = false;            /* true if RTA parse should be used     RT-CO */
65 bool opt_xta = false;           /* true if XTA parse should be used    XTA-CO */
66 bool opt_vta = false;           /* true if VTA parse should be used    VTA-CO */
67 bool opt_verify = true;        /* true if classfiles should be verified      */
68 bool opt_liberalutf = false;   /* Don't check overlong UTF-8 sequences       */
69
70 bool showmethods = false;
71 bool showconstantpool = false;
72 bool showutf = false;
73
74 bool makeinitializations = true;
75
76 bool getloadingtime = false;
77 s8 loadingtime = 0;
78
79
80 /******* replace some external functions  *********/
81  
82 functionptr native_findfunction(utf *cname, utf *mname, utf *desc, bool isstatic)
83 { return NULL; }
84
85 java_objectheader *javastring_new(utf *text)
86 { return NULL; }
87
88 utf *javastring_toutf(java_lang_String *string, bool isclassname)
89 { return NULL; }
90
91
92 /* some exception stuff */
93
94 char *string_java_lang_ClassCircularityError =
95     "java/lang/ClassCircularityError";
96
97 char *string_java_lang_ClassFormatError =
98     "java/lang/ClassFormatError";
99
100 char *string_java_lang_IllegalMonitorStateException =
101     "java/lang/IllegalMonitorStateException";
102
103 char *string_java_lang_LinkageError =
104     "java/lang/LinkageError";
105
106 char *string_java_lang_NegativeArraySizeException =
107     "java/lang/NegativeArraySizeException";
108
109 char *string_java_lang_NoClassDefFoundError =
110     "java/lang/NoClassDefFoundError";
111
112 char *string_java_lang_OutOfMemoryError =
113     "java/lang/OutOfMemoryError";
114
115
116 void throw_exception_exit() {}
117 void new_exception(char *classname) {}
118 void new_exception_message(char *classname, char *message) {}
119 void new_exception_throwable(char *classname, java_objectheader *t) {}
120 void new_exception_utfmessage(char *classname, utf *message)
121 {
122         printf("%s: ", classname);
123         utf_display(message);
124         printf("\n");
125         exit(1);
126 }
127
128 java_objectheader *literalstring_new(utf *u) { return NULL; }  
129
130
131 void literalstring_free(java_objectheader *o) { }
132 void stringtable_update() { }
133 void synchronize_caches() { }
134 void asm_call_jit_compiler() { }
135 void asm_calljavafunction() { }
136 s4 asm_builtin_checkcast(java_objectheader *obj, classinfo *class) { return 0; }
137
138 s4 asm_builtin_idiv(s4 a, s4 b) {return 0;}
139 s4 asm_builtin_irem(s4 a, s4 b) {return 0;}
140 s8 asm_builtin_ldiv(s8 a, s8 b) {return 0;}
141 s8 asm_builtin_lrem(s8 a, s8 b) {return 0;}
142
143 s4 asm_builtin_f2i(float a) { return 0; }
144 s8 asm_builtin_f2l(float a) { return 0; }
145 s4 asm_builtin_d2i(double a) { return 0; }
146 s8 asm_builtin_d2l(double a) { return 0; }
147
148 void asm_builtin_monitorenter(java_objectheader *o) {}
149 void asm_builtin_monitorexit(java_objectheader *o) {}
150
151 s4 asm_builtin_checkarraycast(java_objectheader *obj, vftbl *target) {return 0;}
152
153
154 #if defined(__I386__)
155 s4 asm_builtin_arrayinstanceof(java_objectheader *obj, classinfo *class) { return 0; }
156 void asm_builtin_newarray(s4 size, vftbl *arrayvftbl) {}
157 #endif
158
159 void asm_builtin_aastore(java_objectarray *a, s4 index, java_objectheader *o) {}
160
161 u1 *createcompilerstub(methodinfo *m) {return NULL;}
162 u1 *createnativestub(functionptr f, methodinfo *m) {return NULL;}
163 u1 *oldcreatenativestub(functionptr f, methodinfo *m) {return NULL;}
164
165 void removecompilerstub(u1 *stub) {}
166 void removenativestub(u1 *stub) {}
167
168 void asm_perform_threadswitch(u1 **from, u1 **to, u1 **stackTop) {}
169 u1* asm_initialize_thread_stack(void *func, u1 *stack) { return NULL; }
170 void asm_switchstackandcall() {}
171 void asm_handle_builtin_exception(classinfo *c) {}
172
173 java_objectheader *native_new_and_init(void *p) { return NULL; }
174
175
176 /************************ global variables **********************/
177
178 THREADSPECIFIC java_objectheader *_exceptionptr;
179
180 static chain *nativemethod_chain;    /* chain with native methods     */
181 static chain *nativeclass_chain;                               /* chain with processed classes  */      
182 static chain *ident_chain;        /* chain with method and field names in current class */
183 static FILE *file = NULL;
184 static u4 outputsize;
185 static bool dopadding;
186
187
188 static void printIDpart(int c) 
189 {
190         if ((c >= 'a' && c <= 'z')
191                 || (c >= 'A' && c <= 'Z')
192                 || (c >= '0' && c <= '9')
193                 || (c == '_'))
194                 putc(c, file);
195         else
196                 putc('_', file);
197 }
198
199
200 static void printID(utf *u)
201 {
202         char *utf_ptr = u->text;
203         int i;
204
205         for (i = 0; i < utf_strlen(u); i++) 
206                 printIDpart(utf_nextu2(&utf_ptr));
207 }
208
209
210 static void addoutputsize (int len)
211 {
212         u4 newsize,i;
213         if (!dopadding) return;
214
215         newsize = ALIGN(outputsize, len);
216         
217         for (i = outputsize; i < newsize; i++) fprintf(file, "   u1 pad%d\n", (int) i);
218         outputsize = newsize;
219 }
220
221
222 static char *printtype(char *utf_ptr)
223 {
224         u2 c;
225
226         switch (utf_nextu2(&utf_ptr)) {
227         case 'V': fprintf (file, "void");
228                 break;
229         case 'I':
230         case 'S':
231         case 'B':
232         case 'C':
233         case 'Z': addoutputsize (4);
234                 fprintf (file, "s4");
235                 break;
236         case 'J': addoutputsize (8);
237                 fprintf (file, "s8");
238                 break;
239         case 'F': addoutputsize (4);
240                 fprintf (file, "float");
241                 break;
242         case 'D': addoutputsize (8);
243                 fprintf (file, "double");
244                 break;
245         case '[':
246                 addoutputsize ( sizeof(java_arrayheader*) ); 
247                 switch (utf_nextu2(&utf_ptr)) {
248                 case 'I':  fprintf (file, "java_intarray*"); break;
249                 case 'J':  fprintf (file, "java_longarray*"); break;
250                 case 'Z':  fprintf (file, "java_booleanarray*"); break;
251                 case 'B':  fprintf (file, "java_bytearray*"); break;
252                 case 'S':  fprintf (file, "java_shortarray*"); break;
253                 case 'C':  fprintf (file, "java_chararray*"); break;
254                 case 'F':  fprintf (file, "java_floatarray*"); break;
255                 case 'D':  fprintf (file, "java_doublearray*"); break;
256                                 
257                 case '[':  fprintf (file, "java_objectarray*");                                        
258                         while ((c = utf_nextu2(&utf_ptr)) == '[') ;
259                         if (c=='L') 
260                                 while (utf_nextu2(&utf_ptr) != ';');
261                         break;
262                            
263                 case 'L':  fprintf (file, "java_objectarray*");
264                         while ( utf_nextu2(&utf_ptr) != ';');
265                         break;
266                 default: panic ("invalid type descriptor");
267                 }
268                 break;
269                 
270         case 'L': 
271                 addoutputsize ( sizeof(java_objectheader*));
272                 fprintf (file, "struct ");
273                 while ( (c = utf_nextu2(&utf_ptr)) != ';' ) printIDpart (c);     
274                 fprintf (file, "*");
275                 break;
276                                         
277         default:  panic ("Unknown type in field descriptor");
278         }
279         
280         return utf_ptr;
281 }
282
283
284 /***** determine the number of entries of a utf string in the ident chain *****/
285
286 static int searchidentchain_utf(utf *ident) 
287 {
288         utf *u = chain_first(ident_chain);     /* first element of list */
289         int count = 0;
290
291         while (u) {
292                 if (u==ident) count++;         /* string found */
293                 u = chain_next(ident_chain);   /* next element in list */ 
294         }
295
296         return count;
297 }
298
299
300 /************** print structure for direct access to objects ******************/
301
302 static void printfields(classinfo *c)
303 {
304         u4 i;
305         fieldinfo *f;
306         int ident_count;
307         
308         if (!c) {
309                 addoutputsize(sizeof(java_objectheader));
310                 fprintf(file, "   java_objectheader header;\n");
311                 return;
312         }
313                 
314         printfields(c->super);
315         
316         for (i = 0; i < c->fieldscount; i++) {
317                 f = &(c->fields[i]);
318                 
319                 if (!(f->flags & ACC_STATIC)) {
320                         fprintf(file, "   ");
321                         printtype(f->descriptor->text);
322                         fprintf(file, " ");
323                         utf_fprint(file, f->name);
324
325                         /* rename multiple fieldnames */
326                         if ((ident_count = searchidentchain_utf(f->name)))
327                                 fprintf(file, "%d", ident_count - 1);
328                         chain_addlast(ident_chain, f->name);    
329
330                         fprintf(file, ";\n");
331                 }
332         }
333 }
334
335
336 /***************** store prototype for native method in file ******************/
337
338 static void printmethod(methodinfo *m)
339 {
340         char *utf_ptr;
341         u2 paramnum = 1;
342         u2 ident_count;
343
344         /* search for return-type in descriptor */      
345         utf_ptr = m->descriptor->text;
346         while (utf_nextu2(&utf_ptr) != ')');
347
348         /* create remarks */
349         fprintf(file, "\n/*\n * Class:     ");
350         utf_fprint(file, m->class->name);
351         fprintf(file, "\n * Method:    ");
352         utf_fprint(file, m->name);
353         fprintf(file, "\n * Signature: ");
354         utf_fprint(file, m->descriptor);
355         fprintf(file, "\n */\n");       
356
357         /* create prototype */                  
358         fprintf(file, "JNIEXPORT ");                            
359         printtype(utf_ptr);
360         fprintf(file, " JNICALL Java_");
361         printID(m->class->name);           
362
363         /* rename overloaded method */
364         if ((ident_count = searchidentchain_utf(m->name)))
365                 fprintf(file, "%d", ident_count - 1);           
366         chain_addlast(ident_chain, m->name);    
367
368         fprintf(file, "_");
369         printID(m->name);
370         fprintf(file, "(JNIEnv *env");
371         
372         utf_ptr = m->descriptor->text + 1;
373                         
374         if (!(m->flags & ACC_STATIC)) {
375                 fprintf(file, ", struct ");
376                 printID(m->class->name);
377                 fprintf(file, "* this");
378
379         } else {
380                 fprintf(file, ", jclass clazz");
381         }
382
383         if ((*utf_ptr) != ')') fprintf(file, ", ");
384                         
385         while ((*utf_ptr) != ')') {
386                 utf_ptr = printtype(utf_ptr);
387                 fprintf(file, " par%d", paramnum++);
388                 if ((*utf_ptr)!=')') fprintf(file, ", ");
389         }
390                         
391         fprintf(file, ");\n\n");
392 }
393
394
395 /******* remove package-name in fully-qualified classname *********************/
396
397 static void gen_header_filename(char *buffer, utf *u)
398 {
399         int i;
400   
401         for (i = 0;i < utf_strlen(u); i++) {
402                 if ((u->text[i] == '/') || (u->text[i] == '$')) buffer[i] = '_';  /* convert '$' and '/' to '_' */
403                 else buffer[i] = u->text[i];
404         }
405         buffer[utf_strlen(u)] = '\0';
406 }
407
408
409 /* create headerfile for classes and store native methods in chain ************/
410
411 static void headerfile_generate(classinfo *c)
412 {
413         char header_filename[1024] = "";
414         char classname[1024]; 
415         char uclassname[1024];
416         u2 i;
417         methodinfo *m;                  
418                       
419         /* store class in chain */                    
420         chain_addlast(nativeclass_chain, c);
421                                 
422         /* open headerfile for class */
423         gen_header_filename(classname, c->name);
424
425         /* create chain for renaming fields */
426         ident_chain = chain_new();
427         
428         sprintf(header_filename, "nat/%s.h", classname);
429         file = fopen(header_filename, "w");
430         if (!file) panic("Can not open file to store header information");
431
432         fprintf(file, "/* This file is machine generated, don't edit it !*/\n\n");
433
434         /* convert to uppercase */
435         for (i = 0; classname[i]; i++) {
436                 uclassname[i] = toupper(classname[i]);
437         }
438         uclassname[i] = '\0';
439
440         fprintf(file, "#ifndef _%s_H\n#define _%s_H\n\n", uclassname, uclassname);
441
442         /* create structure for direct access to objects */     
443         fprintf(file, "/* Structure information for class: ");
444         utf_fprint(file, c->name);
445         fprintf(file, " */\n\n");
446         fprintf(file, "typedef struct ");
447         printID(c->name);                                                       
448         fprintf(file, " {\n");
449         outputsize = 0;
450         dopadding = true;
451
452         printfields(c);
453
454         fprintf(file, "} ");
455         printID(c->name);
456         fprintf(file, ";\n\n");
457
458         /* create chain for renaming overloaded methods */
459         chain_free(ident_chain);
460         ident_chain = chain_new();
461
462         /* create method-prototypes */
463                                 
464         for (i = 0; i < c->methodscount; i++) {
465
466                 m = &(c->methods[i]);
467
468                 if (m->flags & ACC_NATIVE) {
469                         chain_addlast(nativemethod_chain, m);
470                         printmethod(m);
471                 }
472         }
473
474         chain_free(ident_chain);
475
476         fprintf(file, "#endif\n\n");
477
478         fclose(file);
479 }
480
481
482 /******** print classname, '$' used to seperate inner-class name ***********/
483
484 void print_classname(classinfo *clazz)
485 {
486         utf *u = clazz->name;
487     char *endpos  = u->text + u->blength;
488     char *utf_ptr = u->text; 
489         u2 c;
490
491     while (utf_ptr < endpos) {
492                 if ((c = utf_nextu2(&utf_ptr)) == '_') {
493                         putc('$', file);
494
495                 } else {
496                         putc(c, file);
497                 }
498         }
499
500
501
502 /*************** create table for locating native functions ****************/
503
504 static void printnativetableentry(methodinfo *m)
505 {
506         fprintf(file, "   { \"");
507         print_classname(m->class);
508         fprintf(file, "\",\n     \"");
509         utf_fprint(file, m->name);
510         fprintf(file, "\",\n     \"");
511         utf_fprint(file, m->descriptor);
512         fprintf(file, "\",\n     ");
513
514         if ((m->flags & ACC_STATIC) != 0)
515                 fprintf(file, "true");
516         else
517                 fprintf(file, "false");
518
519         fprintf(file, ",\n     ");
520         fprintf(file, "(functionptr) Java_");
521         printID(m->class->name);
522         fprintf(file,"_");
523         printID(m->name);
524         fprintf(file,"\n   },\n");
525 }
526
527
528 /***************************************************************************
529
530         create the nativetypes-headerfile which includes 
531         the headerfiles of the classes stored in the classes-chain 
532
533 ****************************************************************************/
534
535 static void headers_finish()
536 {
537         methodinfo *m;
538         classinfo *c;
539         char classname[1024];
540         
541         file = fopen("nativetypes.hh", "w");
542
543         if (!file)
544                 panic("Can not open file 'native.h' to store header information");
545         
546         fprintf(file, "/* Headerfile for native methods: nativetypes.hh */\n");
547         fprintf(file, "/* This file is machine generated, don't edit it !*/\n\n");      
548         fprintf(file, "\n/* include native-Headerfiles */\n\n");
549                         
550         c = chain_first(nativeclass_chain);
551         while (c) {
552                 dopadding = false;
553                 gen_header_filename(classname, c->name);                                                                                                                                                                                        
554                 fprintf(file, "#include \"nat/%s.h\"\n", classname);            
555                 c = chain_next(nativeclass_chain);              
556         }
557
558     fclose(file);
559         chain_free(nativeclass_chain);
560         
561         /* create table of native-methods */
562
563         file = fopen("nativetable.hh", "w");
564
565         if (!file)
566                 panic("Can not open file 'nativetable' to store native-link-table");
567
568         fprintf(file, "/* Table of native methods: nativetables.hh */\n");
569         fprintf(file, "/* This file is machine generated, don't edit it !*/\n\n"); 
570
571         while ((m = chain_first(nativemethod_chain)) != NULL) {
572                 chain_remove(nativemethod_chain);               
573                 printnativetableentry(m);
574         }
575                 
576         chain_free(nativemethod_chain);
577         fclose(file);
578 }
579
580
581 /******************** internal function: print_usage ************************
582
583 Prints usage information for the JAVA header generator to stdout.
584
585 ***************************************************************************/
586
587 static void print_usage()
588 {
589         printf("Usage: cacaoh class [class..]\n");
590 }   
591
592
593
594 /************************** Function: main *******************************
595
596    Main program.
597    
598 **************************************************************************/
599
600 int main(int argc, char **argv)
601 {
602         s4 i,a;
603         char *cp;
604         classinfo *topclass;
605                 
606
607         /********** internal (only used by main) *****************************/
608    
609         char classpath[500] = "";
610         char offsets_filename[1024] = ""; /* phil */
611         u4 heapmaxsize = 1000000;
612         u4 heapstartsize = 100000;
613
614         /*********** options so only headers are generated *******************/
615    
616         makeinitializations = false;
617    
618
619         /************ Collect some info from the environment *****************/
620
621         cp = getenv("CLASSPATH");
622         if (cp) {
623                 strcpy(classpath + strlen(classpath), ":");
624                 strcpy(classpath + strlen(classpath), cp);
625         }
626
627         if (argc < 2) {
628                 print_usage();
629                 exit(10);
630         }
631
632
633         /**************************** Program start **************************/
634
635         log_init(NULL);
636         log_text("Java - header-generator started"); 
637         
638         sprintf(offsets_filename, "jit/%s/offsets.h", ARCH_DIR);
639         file = fopen(offsets_filename, "w");
640         if (file == NULL) {
641                 fprintf(stderr, "Can not open file '%s' for write", offsets_filename);
642                 exit(-1);
643         }
644         
645         fprintf(file, "/* This file is machine generated, don't edit it !*/\n\n"); 
646
647         fprintf(file, "#define offobjvftbl    %3d\n", (int) OFFSET(java_objectheader, vftbl));
648         fprintf(file, "#define offarraysize   %3d\n", (int) OFFSET(java_arrayheader, size));
649         fprintf(file, "#define offobjarrdata  %3d\n\n", (int) OFFSET(java_objectarray, data[0]));
650         fprintf(file, "#define offbaseval     %3d\n", (int) OFFSET(vftbl, baseval));
651         fprintf(file, "#define offdiffval     %3d\n\n", (int) OFFSET(vftbl, diffval));
652
653         fprintf(file, "#define offclassvftbl  %3d\n", (int) OFFSET(classinfo, vftbl));
654         fprintf(file, "#define offclassinit   %3d\n", (int) OFFSET(classinfo, initialized));
655         fprintf(file, "#define offclassloaded %3d\n", (int) OFFSET(classinfo, loaded));
656         fprintf(file, "#define offclasslinked %3d\n\n", (int) OFFSET(classinfo, linked));
657
658         fprintf(file, "#define offjniitemtype %3d\n", (int) OFFSET(jni_callblock, itemtype));
659         fprintf(file, "#define offjniitem     %3d\n", (int) OFFSET(jni_callblock, item));
660         fprintf(file, "#define sizejniblock   %3d\n\n", (int) sizeof(jni_callblock));
661
662         fprintf(file, "#define offclassmethodinfo   %3d\n\n", (int) OFFSET(methodinfo,class));
663
664         fprintf(file, "#define offmethodnative %3d\n", (int) OFFSET(native_stackframeinfo,method));
665         fprintf(file, "#define offreturnfromnative %3d\n", (int) OFFSET(native_stackframeinfo,returnFromNative));
666         fprintf(file, "#define offaddrreturnfromnative %3d\n", (int) OFFSET(native_stackframeinfo,addrReturnFromNative));
667         fprintf(file, "#define offprevnative %3d\n", (int) OFFSET(native_stackframeinfo,prev));
668         fprintf(file, "#define offnextnative %3d\n", (int) OFFSET(native_stackframeinfo,next));
669         
670
671         fclose(file);
672
673         /* initialize the garbage collector */
674         gc_init(heapmaxsize, heapstartsize);
675
676         suck_init(classpath);
677    
678         tables_init();
679
680 #if defined(USE_THREADS) && defined(NATIVE_THREADS)
681         initThreadsEarly();
682 #endif
683         loader_init();
684
685
686         /*********************** Load JAVA classes  **************************/
687         
688         nativemethod_chain = chain_new();
689         nativeclass_chain = chain_new();
690         
691         for (a = 1; a < argc; a++) {
692                 cp = argv[a];
693
694                 /* convert classname */
695                 for (i = strlen(cp) - 1; i >= 0; i--) {
696                         switch (cp[i]) {
697                         case '.': cp[i]='/';
698                                 break;
699                         case '_': cp[i]='$';    
700                         }
701                 }
702         
703 /*              topclass = loader_load(utf_new_char(cp)); */
704                 topclass = class_load(class_new(utf_new_char(cp)));
705                 class_link(topclass);
706
707         headerfile_generate(topclass);
708         }
709
710         headers_finish();
711
712         /************************ Release all resources **********************/
713
714         loader_close();
715         tables_close(literalstring_free);
716
717         /* Print "finished" message */
718
719         log_text("Java - header-generator stopped");
720         log_cputime();
721         mem_usagelog(1);
722         
723         return 0;
724 }
725
726
727 void setVMClassField(classinfo *c)
728 {
729 }
730
731
732 void *Java_java_lang_VMObject_clone(void *env, void *clazz, void * this) {
733         return 0;
734 }
735
736
737 /*
738  * These are local overrides for various environment variables in Emacs.
739  * Please do not remove this and leave it at the end of the file, where
740  * Emacs will automagically detect them.
741  * ---------------------------------------------------------------------
742  * Local variables:
743  * mode: c
744  * indent-tabs-mode: t
745  * c-basic-offset: 4
746  * tab-width: 4
747  * End:
748  */