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