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