Moved getcputime() into statistics.*
[cacao.git] / headers.c
1 /* headers.c - functions for header generation
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             Christian Thalinger
32
33    $Id: headers.c 1244 2004-06-30 20:14:20Z twisti $
34
35 */
36
37
38 #include <stdlib.h>
39 #include <string.h>
40 #include <ctype.h>
41 #include "config.h"
42 #include "global.h"
43 #include "tables.h"
44 #include "loader.h"
45 #include "options.h"
46 #include "builtin.h"
47 #include "mm/boehm.h"
48 #include "toolbox/chain.h"
49 #include "toolbox/memory.h"
50 #include "toolbox/logging.h"
51 #include "nat/java_lang_String.h"
52
53
54 /******* replace some external functions  *********/
55  
56 functionptr native_findfunction(utf *cname, utf *mname, utf *desc, bool isstatic)
57 { return NULL; }
58
59 java_objectheader *javastring_new(utf *text)
60 { return NULL; }
61
62 char *javastring_tochar(java_objectheader *so) { return NULL; }
63 utf *javastring_toutf(java_lang_String *string, bool isclassname)
64 { return NULL; }
65
66
67 /* some exception stuff */
68
69 classinfo *class_java_lang_Exception;
70
71
72 char *string_java_lang_IllegalMonitorStateException =
73     "java/lang/IllegalMonitorStateException";
74
75 char *string_java_lang_NegativeArraySizeException =
76     "java/lang/NegativeArraySizeException";
77
78
79 char *string_java_lang_AbstractMethodError =
80     "java/lang/AbstractMethodError";
81
82 char *string_java_lang_ClassCircularityError =
83     "java/lang/ClassCircularityError";
84
85 char *string_java_lang_ClassFormatError =
86     "java/lang/ClassFormatError";
87
88 char *string_java_lang_ExceptionInInitializerError =
89     "java/lang/ExceptionInInitializerError";
90
91 char *string_java_lang_IncompatibleClassChangeError =
92     "java/lang/IncompatibleClassChangeError";
93
94 char *string_java_lang_InternalError =
95     "java/lang/InternalError";
96
97 char *string_java_lang_LinkageError =
98     "java/lang/LinkageError";
99
100 char *string_java_lang_NoClassDefFoundError =
101     "java/lang/NoClassDefFoundError";
102
103 char *string_java_lang_NoSuchFieldError =
104     "java/lang/NoSuchFieldError";
105
106 char *string_java_lang_NoSuchMethodError =
107         "java/lang/NoSuchMethodError";
108
109 char *string_java_lang_OutOfMemoryError =
110     "java/lang/OutOfMemoryError";
111
112
113 void throw_exception() {}
114 void throw_exception_exit() {}
115
116 void throw_cacao_exception_exit(char *exception, char *message)
117 {
118         fprintf(stderr,
119                         "Exception in thread \"main\" %s: %s\n", exception, message);
120         fflush(stderr);
121
122         /* good bye! */
123         exit(1);
124 }
125
126
127 void new_exception(char *classname)
128 {
129         printf("Exception in thread \"main\" %s\n", classname);
130         exit(1);
131 }
132
133 void new_exception_message(char *classname, char *message)
134 {
135         printf("Exception in thread \"main\" %s: %s\n", classname, message);
136         exit(1);
137 }
138
139 void new_exception_throwable(char *classname, java_objectheader *t) {}
140 void new_exception_utfmessage(char *classname, utf *message)
141 {
142         printf("Exception in thread \"main\" %s: ", classname);
143         utf_display(message);
144         printf("\n");
145         exit(1);
146 }
147
148 java_objectheader *literalstring_new(utf *u) { return NULL; }  
149
150
151 void literalstring_free(java_objectheader *o) {}
152 void stringtable_update() { }
153 void synchronize_caches() { }
154 void asm_call_jit_compiler() { }
155 void asm_calljavafunction() { }
156 s4 asm_builtin_checkcast(java_objectheader *obj, classinfo *class) { return 0; }
157
158 s4 asm_builtin_idiv(s4 a, s4 b) {return 0;}
159 s4 asm_builtin_irem(s4 a, s4 b) {return 0;}
160 s8 asm_builtin_ldiv(s8 a, s8 b) {return 0;}
161 s8 asm_builtin_lrem(s8 a, s8 b) {return 0;}
162
163 s4 asm_builtin_f2i(float a) { return 0; }
164 s8 asm_builtin_f2l(float a) { return 0; }
165 s4 asm_builtin_d2i(double a) { return 0; }
166 s8 asm_builtin_d2l(double a) { return 0; }
167
168 void asm_builtin_monitorenter(java_objectheader *o) {}
169 void asm_builtin_monitorexit(java_objectheader *o) {}
170
171 s4 asm_builtin_checkarraycast(java_objectheader *obj, vftbl *target) {return 0;}
172
173 #if defined(__MIPS__)
174 void atomic_swap() {}
175 void compare_and_swap() {}
176 #endif
177
178
179 #if defined(__I386__)
180 s4 asm_builtin_arrayinstanceof(java_objectheader *obj, classinfo *class) { return 0; }
181 void asm_builtin_newarray(s4 size, vftbl *arrayvftbl) {}
182 #endif
183
184 void asm_builtin_aastore(java_objectarray *a, s4 index, java_objectheader *o) {}
185
186 u1 *createcompilerstub(methodinfo *m) {return NULL;}
187 u1 *createnativestub(functionptr f, methodinfo *m) {return NULL;}
188 u1 *oldcreatenativestub(functionptr f, methodinfo *m) {return NULL;}
189
190 void removecompilerstub(u1 *stub) {}
191 void removenativestub(u1 *stub) {}
192
193 void asm_perform_threadswitch(u1 **from, u1 **to, u1 **stackTop) {}
194 u1* asm_initialize_thread_stack(void *func, u1 *stack) { return NULL; }
195 void thread_restartcriticalsection() {}
196 void asm_switchstackandcall() {}
197 void asm_handle_builtin_exception(classinfo *c) {}
198 void asm_getclassvalues_atomic() {}
199
200 #if defined(__DARWIN__)
201 int cacao_catch_Handler() {}
202 #endif
203
204 #if defined(USE_THREADS) && defined(NATIVE_THREADS)
205 threadcritnode asm_criticalsections;
206 #endif
207
208 java_objectheader *native_new_and_init(void *p) { return NULL; }
209
210
211 /************************ global variables **********************/
212
213 THREADSPECIFIC java_objectheader *_exceptionptr;
214
215 chain *nativemethod_chain;              /* chain with native methods          */
216 chain *nativeclass_chain;               /* chain with processed classes       */
217 static chain *ident_chain; /* chain with method and field names in current class */
218 FILE *file = NULL;
219 static u4 outputsize;
220 static bool dopadding;
221
222
223 static void printIDpart(int c) 
224 {
225         if ((c >= 'a' && c <= 'z')
226                 || (c >= 'A' && c <= 'Z')
227                 || (c >= '0' && c <= '9')
228                 || (c == '_'))
229                 putc(c, file);
230         else
231                 putc('_', file);
232 }
233
234
235 static void printID(utf *u)
236 {
237         char *utf_ptr = u->text;
238         int i;
239
240         for (i = 0; i < utf_strlen(u); i++) 
241                 printIDpart(utf_nextu2(&utf_ptr));
242 }
243
244
245 static void addoutputsize (int len)
246 {
247         u4 newsize,i;
248         if (!dopadding) return;
249
250         newsize = ALIGN(outputsize, len);
251         
252         for (i = outputsize; i < newsize; i++) fprintf(file, "   u1 pad%d\n", (int) i);
253         outputsize = newsize;
254 }
255
256 static void printOverloadPart(utf *desc)
257 {
258         char *utf_ptr=desc->text;
259         u2 c;
260
261         fprintf(file,"__");
262         while ((c=utf_nextu2(&utf_ptr))!=')') {
263                 switch (c) {
264                         case 'I':
265                         case 'S':
266                         case 'B':
267                         case 'C':
268                         case 'Z':
269                         case 'J':
270                         case 'F':
271                         case 'D': 
272                                 fprintf (file, "%c",(char)c);
273                                 break;
274                         case '[':
275                                 fprintf(file,"_3");
276                                 break;
277                         case 'L':
278                                 putc('L',file);
279                                 while ( (c=utf_nextu2(&utf_ptr)) != ';')
280                                         printIDpart (c);
281                                 fprintf(file,"_2");
282                                 break;
283                         case '(':
284                                 break;
285                         default: panic ("invalid method descriptor");
286                 }
287         }
288 }
289
290 static char *printtype(char *utf_ptr)
291 {
292         u2 c;
293
294         switch (utf_nextu2(&utf_ptr)) {
295         case 'V': fprintf (file, "void");
296                 break;
297         case 'I':
298         case 'S':
299         case 'B':
300         case 'C':
301         case 'Z': addoutputsize (4);
302                 fprintf (file, "s4");
303                 break;
304         case 'J': addoutputsize (8);
305                 fprintf (file, "s8");
306                 break;
307         case 'F': addoutputsize (4);
308                 fprintf (file, "float");
309                 break;
310         case 'D': addoutputsize (8);
311                 fprintf (file, "double");
312                 break;
313         case '[':
314                 addoutputsize ( sizeof(java_arrayheader*) ); 
315                 switch (utf_nextu2(&utf_ptr)) {
316                 case 'I':  fprintf (file, "java_intarray*"); break;
317                 case 'J':  fprintf (file, "java_longarray*"); break;
318                 case 'Z':  fprintf (file, "java_booleanarray*"); break;
319                 case 'B':  fprintf (file, "java_bytearray*"); break;
320                 case 'S':  fprintf (file, "java_shortarray*"); break;
321                 case 'C':  fprintf (file, "java_chararray*"); break;
322                 case 'F':  fprintf (file, "java_floatarray*"); break;
323                 case 'D':  fprintf (file, "java_doublearray*"); break;
324                                 
325                 case '[':  fprintf (file, "java_objectarray*");                                        
326                         while ((c = utf_nextu2(&utf_ptr)) == '[') ;
327                         if (c=='L') 
328                                 while (utf_nextu2(&utf_ptr) != ';');
329                         break;
330                            
331                 case 'L':  fprintf (file, "java_objectarray*");
332                         while ( utf_nextu2(&utf_ptr) != ';');
333                         break;
334                 default: panic ("invalid type descriptor");
335                 }
336                 break;
337                 
338         case 'L': 
339                 addoutputsize ( sizeof(java_objectheader*));
340                 fprintf (file, "struct ");
341                 while ( (c = utf_nextu2(&utf_ptr)) != ';' ) printIDpart (c);     
342                 fprintf (file, "*");
343                 break;
344                                         
345         default:  panic ("Unknown type in field descriptor");
346         }
347         
348         return utf_ptr;
349 }
350
351
352 /***** determine the number of entries of a utf string in the ident chain *****/
353
354 static int searchidentchain_utf(utf *ident) 
355 {
356         utf *u = chain_first(ident_chain);     /* first element of list */
357         int count = 0;
358
359         while (u) {
360                 if (u==ident) count++;         /* string found */
361                 u = chain_next(ident_chain);   /* next element in list */ 
362         }
363
364         return count;
365 }
366
367
368 /************** print structure for direct access to objects ******************/
369
370 static void printfields(classinfo *c)
371 {
372         u4 i;
373         fieldinfo *f;
374         int ident_count;
375         
376         if (!c) {
377                 addoutputsize(sizeof(java_objectheader));
378                 fprintf(file, "   java_objectheader header;\n");
379                 return;
380         }
381                 
382         printfields(c->super);
383         
384         for (i = 0; i < c->fieldscount; i++) {
385                 f = &(c->fields[i]);
386                 
387                 if (!(f->flags & ACC_STATIC)) {
388                         fprintf(file, "   ");
389                         printtype(f->descriptor->text);
390                         fprintf(file, " ");
391                         utf_fprint(file, f->name);
392
393                         /* rename multiple fieldnames */
394                         if ((ident_count = searchidentchain_utf(f->name)))
395                                 fprintf(file, "%d", ident_count - 1);
396                         chain_addlast(ident_chain, f->name);    
397
398                         fprintf(file, ";\n");
399                 }
400         }
401 }
402
403
404 /***************** store prototype for native method in file ******************/
405
406 void printmethod(methodinfo *m)
407 {
408         char *utf_ptr;
409         u2 paramnum = 1;
410         u2 ident_count;
411
412         /* search for return-type in descriptor */      
413         utf_ptr = m->descriptor->text;
414         while (utf_nextu2(&utf_ptr) != ')');
415
416         /* create remarks */
417         fprintf(file, "\n/*\n * Class:     ");
418         utf_fprint(file, m->class->name);
419         fprintf(file, "\n * Method:    ");
420         utf_fprint(file, m->name);
421         fprintf(file, "\n * Signature: ");
422         utf_fprint(file, m->descriptor);
423         fprintf(file, "\n */\n");       
424
425         /* create prototype */                  
426         fprintf(file, "JNIEXPORT ");                            
427         printtype(utf_ptr);
428         fprintf(file, " JNICALL Java_");
429         printID(m->class->name);           
430
431         chain_addlast(ident_chain, m->name);    
432
433         fprintf(file, "_");
434         printID(m->name);
435         if (m->nativelyoverloaded) printOverloadPart(m->descriptor);
436         fprintf(file, "(JNIEnv *env");
437         
438         utf_ptr = m->descriptor->text + 1;
439                         
440         if (!(m->flags & ACC_STATIC)) {
441                 fprintf(file, ", struct ");
442                 printID(m->class->name);
443                 fprintf(file, "* this");
444
445         } else {
446                 fprintf(file, ", jclass clazz");
447         }
448
449         if ((*utf_ptr) != ')') fprintf(file, ", ");
450                         
451         while ((*utf_ptr) != ')') {
452                 utf_ptr = printtype(utf_ptr);
453                 fprintf(file, " par%d", paramnum++);
454                 if ((*utf_ptr)!=')') fprintf(file, ", ");
455         }
456                         
457         fprintf(file, ");\n\n");
458 }
459
460
461 /******* remove package-name in fully-qualified classname *********************/
462
463 void gen_header_filename(char *buffer, utf *u)
464 {
465         s4 i;
466   
467         for (i = 0; i < utf_strlen(u); i++) {
468                 if ((u->text[i] == '/') || (u->text[i] == '$')) {
469                         buffer[i] = '_';  /* convert '$' and '/' to '_' */
470
471                 } else {
472                         buffer[i] = u->text[i];
473                 }
474         }
475         buffer[utf_strlen(u)] = '\0';
476 }
477
478
479 /* create headerfile for classes and store native methods in chain ************/
480
481 void headerfile_generate(classinfo *c)
482 {
483         char header_filename[1024] = "";
484         char classname[1024]; 
485         char uclassname[1024];
486         u2 i;
487         methodinfo *m;                  
488         u2 i2;
489         methodinfo *m2;
490         u2 nativelyoverloaded;                  
491                       
492         /* store class in chain */                    
493         chain_addlast(nativeclass_chain, c);
494                                 
495         /* open headerfile for class */
496         gen_header_filename(classname, c->name);
497
498         /* create chain for renaming fields */
499         ident_chain = chain_new();
500         
501         sprintf(header_filename, "nat/%s.h", classname);
502         file = fopen(header_filename, "w");
503         if (!file) panic("Can not open file to store header information");
504
505         fprintf(file, "/* This file is machine generated, don't edit it !*/\n\n");
506
507         /* convert to uppercase */
508         for (i = 0; classname[i]; i++) {
509                 uclassname[i] = toupper(classname[i]);
510         }
511         uclassname[i] = '\0';
512
513         fprintf(file, "#ifndef _%s_H\n#define _%s_H\n\n", uclassname, uclassname);
514
515         /* create structure for direct access to objects */     
516         fprintf(file, "/* Structure information for class: ");
517         utf_fprint(file, c->name);
518         fprintf(file, " */\n\n");
519         fprintf(file, "typedef struct ");
520         printID(c->name);                                                       
521         fprintf(file, " {\n");
522         outputsize = 0;
523         dopadding = true;
524
525         printfields(c);
526
527         fprintf(file, "} ");
528         printID(c->name);
529         fprintf(file, ";\n\n");
530
531         /* create chain for renaming overloaded methods */
532         chain_free(ident_chain);
533         ident_chain = chain_new();
534
535         /* create method-prototypes */
536                                 
537         /* find overloaded methods */
538         for (i = 0; i < c->methodscount; i++) {
539
540                 m = &(c->methods[i]);
541
542                 if (!(m->flags & ACC_NATIVE)) continue;
543                 if (!m->nativelyoverloaded) {
544                         nativelyoverloaded=false;
545                         for (i2=i+1;i2<c->methodscount; i2++) {
546                                 m2 = &(c->methods[i2]);
547                                 if (!(m2->flags & ACC_NATIVE)) continue;
548                                 if (m->name==m2->name) {
549                                         m2->nativelyoverloaded=true;
550                                         nativelyoverloaded=true;
551                                 }
552                         }
553                         m->nativelyoverloaded=nativelyoverloaded;
554                 }
555
556         }
557
558         for (i = 0; i < c->methodscount; i++) {
559
560                 m = &(c->methods[i]);
561
562                 if (m->flags & ACC_NATIVE) {
563                         chain_addlast(nativemethod_chain, m);
564                         printmethod(m);
565                 }
566         }
567
568         chain_free(ident_chain);
569
570         fprintf(file, "#endif\n\n");
571
572         fclose(file);
573 }
574
575
576 /******** print classname, '$' used to seperate inner-class name ***********/
577
578 void print_classname(classinfo *clazz)
579 {
580         utf *u = clazz->name;
581     char *endpos  = u->text + u->blength;
582     char *utf_ptr = u->text; 
583         u2 c;
584
585     while (utf_ptr < endpos) {
586                 if ((c = utf_nextu2(&utf_ptr)) == '_') {
587                         putc('$', file);
588
589                 } else {
590                         putc(c, file);
591                 }
592         }
593
594
595
596 /*************** create table for locating native functions ****************/
597
598 void printnativetableentry(methodinfo *m)
599 {
600         fprintf(file, "   { \"");
601         print_classname(m->class);
602         fprintf(file, "\",\n     \"");
603         utf_fprint(file, m->name);
604         fprintf(file, "\",\n     \"");
605         utf_fprint(file, m->descriptor);
606         fprintf(file, "\",\n     ");
607
608         if ((m->flags & ACC_STATIC) != 0)
609                 fprintf(file, "true");
610         else
611                 fprintf(file, "false");
612
613         fprintf(file, ",\n     ");
614         fprintf(file, "(functionptr) Java_");
615         printID(m->class->name);
616         fprintf(file,"_");
617         printID(m->name);
618         if (m->nativelyoverloaded) printOverloadPart(m->descriptor);
619         fprintf(file,"\n   },\n");
620 }
621
622
623 void setVMClassField(classinfo *c)
624 {
625 }
626
627
628 void *Java_java_lang_VMObject_clone(void *env, void *clazz, void * this) {
629         return 0;
630 }
631
632
633 /*
634  * These are local overrides for various environment variables in Emacs.
635  * Please do not remove this and leave it at the end of the file, where
636  * Emacs will automagically detect them.
637  * ---------------------------------------------------------------------
638  * Local variables:
639  * mode: c
640  * indent-tabs-mode: t
641  * c-basic-offset: 4
642  * tab-width: 4
643  * End:
644  */