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