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