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