Added proper asm_builtin_new.
[cacao.git] / src / cacaoh / headers.c
1 /* src/cacaoh/headers.c - functions for header generation
2
3    Copyright (C) 1996-2005 R. Grafl, A. Krall, C. Kruegel, C. Oates,
4    R. Obermaisser, M. Platter, M. Probst, S. Ring, E. Steiner,
5    C. Thalinger, D. Thuernbeck, P. Tomsich, C. Ullrich, J. Wenninger,
6    Institut f. Computersprachen - TU Wien
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 2249 2005-04-06 16:06:48Z twisti $
34
35 */
36
37
38 #include <stdlib.h>
39 #include <string.h>
40 #include <ctype.h>
41
42 #include "config.h"
43
44 #if defined(USE_THREADS) && defined(NATIVE_THREADS)
45 # if defined(__DARWIN__)
46 #  include <signal.h>
47 # endif
48 # include <ucontext.h>
49 #endif
50
51 #include "mm/boehm.h"
52 #include "mm/memory.h"
53 #include "native/include/java_lang_String.h"
54 #include "native/include/java_lang_Throwable.h"
55 #include "toolbox/chain.h"
56 #include "toolbox/logging.h"
57 #include "vm/class.h"
58 #include "vm/global.h"
59 #include "vm/method.h"
60 #include "vm/tables.h"
61 #include "vm/loader.h"
62 #include "vm/options.h"
63 #include "vm/builtin.h"
64 #include "vm/jit/asmpart.h"
65
66
67 /******* replace some external functions  *********/
68  
69 functionptr native_findfunction(utf *cname, utf *mname, utf *desc, bool isstatic)
70 { return NULL; }
71
72 java_objectheader *native_new_and_init(classinfo *c) { return NULL; }
73 java_objectheader *native_new_and_init_string(classinfo *c, java_lang_String *s) { return NULL; }
74 java_objectheader *native_new_and_init_int(classinfo *c, s4 i) { return NULL; }
75 java_objectheader *native_new_and_init_throwable(classinfo *c, java_lang_Throwable *t) { return NULL; }
76
77
78 java_objectheader *asm_calljavafunction(methodinfo *m, void *arg1, void *arg2,
79                                                                                 void *arg3, void *arg4) { return NULL; }
80
81 void asm_call_jit_compiler(void) {}
82
83 /* assembler code patching functions */
84 void asm_builtin_new(unresolved_class *uc) {}
85
86 s4 asm_builtin_checkcast(java_objectheader *obj, classinfo *class) { return 0; }
87
88 s4 asm_builtin_idiv(s4 a, s4 b) { return 0; }
89 s4 asm_builtin_irem(s4 a, s4 b) { return 0; }
90 s8 asm_builtin_ldiv(s8 a, s8 b) { return 0; }
91 s8 asm_builtin_lrem(s8 a, s8 b) { return 0; }
92
93 s4 asm_builtin_f2i(float a) { return 0; }
94 s8 asm_builtin_f2l(float a) { return 0; }
95 s4 asm_builtin_d2i(double a) { return 0; }
96 s8 asm_builtin_d2l(double a) { return 0; }
97
98 void use_class_as_object(void) {}
99 void asm_builtin_monitorenter(java_objectheader *o) {}
100 void *asm_builtin_monitorexit(java_objectheader *o) { return NULL; }
101
102 s4 asm_builtin_checkarraycast(java_objectheader *obj, vftbl_t *target) {
103         return 0;
104 }
105
106 #if defined(__MIPS__)
107 long compare_and_swap(long *p, long oldval, long newval)
108 {
109         if (*p == oldval) {
110                 *p = newval;
111                 return oldval;
112         } else
113                 return *p;
114 }
115 #endif
116
117
118 #if defined(__I386__)
119 s4 asm_builtin_arrayinstanceof(java_objectheader *obj, classinfo *class) {
120         return 0;
121 }
122 void asm_builtin_newarray(s4 size, vftbl_t *arrayvftbl) {}
123 #endif
124
125 void asm_builtin_aastore(java_objectarray *a, s4 index, java_objectheader *o) {}
126
127 u1 *createcompilerstub(methodinfo *m) { return NULL; }
128 u1 *createnativestub(functionptr f, methodinfo *m) { return NULL; }
129 u1 *oldcreatenativestub(functionptr f, methodinfo *m) { return NULL; }
130
131 void removecompilerstub(u1 *stub) {}
132 void removenativestub(u1 *stub) {}
133
134 void asm_perform_threadswitch(u1 **from, u1 **to, u1 **stackTop) {}
135 u1* asm_initialize_thread_stack(void *func, u1 *stack) { return NULL; }
136
137 void *asm_switchstackandcall(void *stack, void *func, void **stacktopsave, void * p) { return NULL; }
138
139 void asm_handle_builtin_exception(classinfo *c) {}
140 void asm_getclassvalues_atomic(vftbl_t *super, vftbl_t *sub, castinfo *out) {}
141
142 #if defined(__DARWIN__)
143 int cacao_catch_Handler(void) {}
144 #endif
145
146 #if defined(USE_THREADS) && defined(NATIVE_THREADS)
147 threadcritnode asm_criticalsections;
148 void thread_restartcriticalsection(ucontext_t *uc) {}
149 #endif
150
151
152 void setVMClassField(classinfo *c) {}
153 void *Java_java_lang_VMObject_clone(void *env, void *clazz, void * this)
154 {
155         return NULL;
156 }
157
158 tristate_t
159 typeinfo_is_assignable_to_class(typeinfo *value,classref_or_classinfo dest)
160 {
161         return true;
162 }
163
164 /************************ global variables **********************/
165
166 chain *nativemethod_chain;              /* chain with native methods          */
167 chain *nativeclass_chain;               /* chain with processed classes       */
168 static chain *ident_chain; /* chain with method and field names in current class */
169 FILE *file = NULL;
170 static u4 outputsize;
171 static bool dopadding;
172
173
174 static void printIDpart(int c)
175 {
176         if ((c >= 'a' && c <= 'z')
177                 || (c >= 'A' && c <= 'Z')
178                 || (c >= '0' && c <= '9')
179                 || (c == '_'))
180                 putc(c, file);
181         else
182                 putc('_', file);
183 }
184
185
186 static void printID(utf *u)
187 {
188         char *utf_ptr = u->text;
189         int i;
190
191         for (i = 0; i < utf_strlen(u); i++) 
192                 printIDpart(utf_nextu2(&utf_ptr));
193 }
194
195
196 static void addoutputsize (int len)
197 {
198         u4 newsize,i;
199         if (!dopadding) return;
200
201         newsize = ALIGN(outputsize, len);
202         
203         for (i = outputsize; i < newsize; i++) fprintf(file, "   u1 pad%d\n", (int) i);
204         outputsize = newsize;
205 }
206
207
208 static void printOverloadPart(utf *desc)
209 {
210         char *utf_ptr=desc->text;
211         u2 c;
212
213         fprintf(file,"__");
214         while ((c=utf_nextu2(&utf_ptr))!=')') {
215                 switch (c) {
216                         case 'I':
217                         case 'S':
218                         case 'B':
219                         case 'C':
220                         case 'Z':
221                         case 'J':
222                         case 'F':
223                         case 'D': 
224                                 fprintf (file, "%c",(char)c);
225                                 break;
226                         case '[':
227                                 fprintf(file,"_3");
228                                 break;
229                         case 'L':
230                                 putc('L',file);
231                                 while ( (c=utf_nextu2(&utf_ptr)) != ';')
232                                         printIDpart (c);
233                                 fprintf(file,"_2");
234                                 break;
235                         case '(':
236                                 break;
237                         default: panic ("invalid method descriptor");
238                 }
239         }
240 }
241
242 static char *printtype(char *utf_ptr)
243 {
244         u2 c;
245
246         switch (utf_nextu2(&utf_ptr)) {
247         case 'V': fprintf (file, "void");
248                 break;
249         case 'I':
250         case 'S':
251         case 'B':
252         case 'C':
253         case 'Z': addoutputsize (4);
254                 fprintf (file, "s4");
255                 break;
256         case 'J': addoutputsize (8);
257                 fprintf (file, "s8");
258                 break;
259         case 'F': addoutputsize (4);
260                 fprintf (file, "float");
261                 break;
262         case 'D': addoutputsize (8);
263                 fprintf (file, "double");
264                 break;
265         case '[':
266                 addoutputsize ( sizeof(java_arrayheader*) ); 
267                 switch (utf_nextu2(&utf_ptr)) {
268                 case 'I':  fprintf (file, "java_intarray*"); break;
269                 case 'J':  fprintf (file, "java_longarray*"); break;
270                 case 'Z':  fprintf (file, "java_booleanarray*"); break;
271                 case 'B':  fprintf (file, "java_bytearray*"); break;
272                 case 'S':  fprintf (file, "java_shortarray*"); break;
273                 case 'C':  fprintf (file, "java_chararray*"); break;
274                 case 'F':  fprintf (file, "java_floatarray*"); break;
275                 case 'D':  fprintf (file, "java_doublearray*"); break;
276                                 
277                 case '[':  fprintf (file, "java_objectarray*");                                        
278                         while ((c = utf_nextu2(&utf_ptr)) == '[') ;
279                         if (c=='L') 
280                                 while (utf_nextu2(&utf_ptr) != ';');
281                         break;
282                            
283                 case 'L':  fprintf (file, "java_objectarray*");
284                         while ( utf_nextu2(&utf_ptr) != ';');
285                         break;
286                 default: panic ("invalid type descriptor");
287                 }
288                 break;
289                 
290         case 'L': 
291                 addoutputsize ( sizeof(java_objectheader*));
292                 fprintf (file, "struct ");
293                 while ( (c = utf_nextu2(&utf_ptr)) != ';' ) printIDpart (c);     
294                 fprintf (file, "*");
295                 break;
296                                         
297         default:  panic ("Unknown type in field descriptor");
298         }
299         
300         return utf_ptr;
301 }
302
303
304 /***** determine the number of entries of a utf string in the ident chain *****/
305
306 static int searchidentchain_utf(utf *ident) 
307 {
308         utf *u = chain_first(ident_chain);     /* first element of list */
309         int count = 0;
310
311         while (u) {
312                 if (u==ident) count++;         /* string found */
313                 u = chain_next(ident_chain);   /* next element in list */ 
314         }
315
316         return count;
317 }
318
319
320 /************** print structure for direct access to objects ******************/
321
322 static void printfields(classinfo *c)
323 {
324         u4 i;
325         fieldinfo *f;
326         int ident_count;
327         
328         if (!c) {
329                 addoutputsize(sizeof(java_objectheader));
330                 fprintf(file, "   java_objectheader header;\n");
331                 return;
332         }
333                 
334         printfields(c->super.cls);
335         
336         for (i = 0; i < c->fieldscount; i++) {
337                 f = &(c->fields[i]);
338                 
339                 if (!(f->flags & ACC_STATIC)) {
340                         fprintf(file, "   ");
341                         printtype(f->descriptor->text);
342                         fprintf(file, " ");
343                         utf_fprint(file, f->name);
344
345                         /* rename multiple fieldnames */
346                         if ((ident_count = searchidentchain_utf(f->name)))
347                                 fprintf(file, "%d", ident_count - 1);
348                         chain_addlast(ident_chain, f->name);    
349
350                         fprintf(file, ";\n");
351                 }
352         }
353 }
354
355
356 /***************** store prototype for native method in file ******************/
357
358 void printmethod(methodinfo *m)
359 {
360         char *utf_ptr;
361         u2 paramnum = 1;
362
363         /* search for return-type in descriptor */      
364         utf_ptr = m->descriptor->text;
365         while (utf_nextu2(&utf_ptr) != ')');
366
367         /* create remarks */
368         fprintf(file, "\n/*\n * Class:     ");
369         utf_fprint(file, m->class->name);
370         fprintf(file, "\n * Method:    ");
371         utf_fprint(file, m->name);
372         fprintf(file, "\n * Signature: ");
373         utf_fprint(file, m->descriptor);
374         fprintf(file, "\n */\n");       
375
376         /* create prototype */                  
377         fprintf(file, "JNIEXPORT ");                            
378         printtype(utf_ptr);
379         fprintf(file, " JNICALL Java_");
380         printID(m->class->name);           
381
382         chain_addlast(ident_chain, m->name);    
383
384         fprintf(file, "_");
385         printID(m->name);
386         if (m->nativelyoverloaded) printOverloadPart(m->descriptor);
387         fprintf(file, "(JNIEnv *env");
388         
389         utf_ptr = m->descriptor->text + 1;
390                         
391         if (!(m->flags & ACC_STATIC)) {
392                 fprintf(file, ", struct ");
393                 printID(m->class->name);
394                 fprintf(file, "* this");
395
396         } else {
397                 fprintf(file, ", jclass clazz");
398         }
399
400         if ((*utf_ptr) != ')') fprintf(file, ", ");
401                         
402         while ((*utf_ptr) != ')') {
403                 utf_ptr = printtype(utf_ptr);
404                 fprintf(file, " par%d", paramnum++);
405                 if ((*utf_ptr)!=')') fprintf(file, ", ");
406         }
407                         
408         fprintf(file, ");\n\n");
409 }
410
411
412 /******* remove package-name in fully-qualified classname *********************/
413
414 void gen_header_filename(char *buffer, utf *u)
415 {
416         s4 i;
417   
418         for (i = 0; i < utf_strlen(u); i++) {
419                 if ((u->text[i] == '/') || (u->text[i] == '$')) {
420                         buffer[i] = '_';  /* convert '$' and '/' to '_' */
421
422                 } else {
423                         buffer[i] = u->text[i];
424                 }
425         }
426         buffer[utf_strlen(u)] = '\0';
427 }
428
429
430 /* create headerfile for classes and store native methods in chain ************/
431
432 void headerfile_generate(classinfo *c, char *opt_directory)
433 {
434         char header_filename[1024] = "";
435         char classname[1024]; 
436         char uclassname[1024];
437         u2 i;
438         methodinfo *m;                  
439         u2 i2;
440         methodinfo *m2;
441         u2 nativelyoverloaded;                  
442                       
443         /* store class in chain */                    
444         chain_addlast(nativeclass_chain, c);
445                                 
446         /* open headerfile for class */
447         gen_header_filename(classname, c->name);
448
449         /* create chain for renaming fields */
450         ident_chain = chain_new();
451         
452         if (opt_directory) {
453                 sprintf(header_filename, "%s/%s.h", opt_directory, classname);
454
455         } else {
456                 sprintf(header_filename, "%s.h", classname);
457         }
458
459         file = fopen(header_filename, "w");
460         if (!file)
461                 panic("Can not open file to store header information");
462
463         fprintf(file, "/* This file is machine generated, don't edit it !*/\n\n");
464
465         /* convert to uppercase */
466         for (i = 0; classname[i]; i++) {
467                 uclassname[i] = toupper(classname[i]);
468         }
469         uclassname[i] = '\0';
470
471         fprintf(file, "#ifndef _%s_H\n#define _%s_H\n\n", uclassname, uclassname);
472
473         /* create structure for direct access to objects */     
474         fprintf(file, "/* Structure information for class: ");
475         utf_fprint(file, c->name);
476         fprintf(file, " */\n\n");
477         fprintf(file, "typedef struct ");
478         printID(c->name);                                                       
479         fprintf(file, " {\n");
480         outputsize = 0;
481         dopadding = true;
482
483         printfields(c);
484
485         fprintf(file, "} ");
486         printID(c->name);
487         fprintf(file, ";\n\n");
488
489         /* create chain for renaming overloaded methods */
490         chain_free(ident_chain);
491         ident_chain = chain_new();
492
493         /* create method-prototypes */
494                                 
495         /* find overloaded methods */
496         for (i = 0; i < c->methodscount; i++) {
497
498                 m = &(c->methods[i]);
499
500                 if (!(m->flags & ACC_NATIVE)) continue;
501                 if (!m->nativelyoverloaded) {
502                         nativelyoverloaded=false;
503                         for (i2=i+1;i2<c->methodscount; i2++) {
504                                 m2 = &(c->methods[i2]);
505                                 if (!(m2->flags & ACC_NATIVE)) continue;
506                                 if (m->name==m2->name) {
507                                         m2->nativelyoverloaded=true;
508                                         nativelyoverloaded=true;
509                                 }
510                         }
511                         m->nativelyoverloaded=nativelyoverloaded;
512                 }
513
514         }
515
516         for (i = 0; i < c->methodscount; i++) {
517
518                 m = &(c->methods[i]);
519
520                 if (m->flags & ACC_NATIVE) {
521                         chain_addlast(nativemethod_chain, m);
522                         printmethod(m);
523                 }
524         }
525
526         chain_free(ident_chain);
527
528         fprintf(file, "#endif\n\n");
529
530         fclose(file);
531 }
532
533
534 /******** print classname, '$' used to seperate inner-class name ***********/
535
536 void print_classname(classinfo *clazz)
537 {
538         utf *u = clazz->name;
539     char *endpos  = u->text + u->blength;
540     char *utf_ptr = u->text; 
541         u2 c;
542
543     while (utf_ptr < endpos) {
544                 if ((c = utf_nextu2(&utf_ptr)) == '_') {
545                         putc('$', file);
546
547                 } else {
548                         putc(c, file);
549                 }
550         }
551
552
553
554 /*
555  * These are local overrides for various environment variables in Emacs.
556  * Please do not remove this and leave it at the end of the file, where
557  * Emacs will automagically detect them.
558  * ---------------------------------------------------------------------
559  * Local variables:
560  * mode: c
561  * indent-tabs-mode: t
562  * c-basic-offset: 4
563  * tab-width: 4
564  * End:
565  */