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