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