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