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