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