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