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