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