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