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