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