1 /* headers.c - main for header generation (cacaoh)
3 Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003
4 R. Grafl, A. Krall, C. Kruegel, C. Oates, R. Obermaisser,
5 M. Probst, S. Ring, E. Steiner, C. Thalinger, D. Thuernbeck,
6 P. Tomsich, J. Wenninger
8 This file is part of CACAO.
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.
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.
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
25 Contact: cacao@complang.tuwien.ac.at
27 Authors: Reinhard Grafl
32 $Id: headers.c 1220 2004-06-29 14:38:55Z twisti $
46 #include "toolbox/chain.h"
47 #include "toolbox/memory.h"
48 #include "toolbox/logging.h"
49 #include "nat/java_lang_String.h"
52 /* replace command line options */
55 bool verboseexception = false;
56 bool compileall = false;
57 bool runverbose = false;
58 bool collectverbose = false;
60 bool loadverbose = false;
61 bool linkverbose = false;
62 bool initverbose = false;
64 bool opt_rt = false; /* true if RTA parse should be used RT-CO */
65 bool opt_xta = false; /* true if XTA parse should be used XTA-CO */
66 bool opt_vta = false; /* true if VTA parse should be used VTA-CO */
67 bool opt_verify = true; /* true if classfiles should be verified */
68 bool opt_liberalutf = false; /* Don't check overlong UTF-8 sequences */
70 bool opt_stat = false;
71 bool opt_eager = false;
73 bool showmethods = false;
74 bool showconstantpool = false;
77 bool makeinitializations = true;
79 bool getloadingtime = false;
83 /******* replace some external functions *********/
85 functionptr native_findfunction(utf *cname, utf *mname, utf *desc, bool isstatic)
88 java_objectheader *javastring_new(utf *text)
91 char *javastring_tochar(java_objectheader *so) { return NULL; }
92 utf *javastring_toutf(java_lang_String *string, bool isclassname)
96 /* some exception stuff */
98 classinfo *class_java_lang_Exception;
101 char *string_java_lang_IllegalMonitorStateException =
102 "java/lang/IllegalMonitorStateException";
104 char *string_java_lang_NegativeArraySizeException =
105 "java/lang/NegativeArraySizeException";
108 char *string_java_lang_AbstractMethodError =
109 "java/lang/AbstractMethodError";
111 char *string_java_lang_ClassCircularityError =
112 "java/lang/ClassCircularityError";
114 char *string_java_lang_ClassFormatError =
115 "java/lang/ClassFormatError";
117 char *string_java_lang_ExceptionInInitializerError =
118 "java/lang/ExceptionInInitializerError";
120 char *string_java_lang_IncompatibleClassChangeError =
121 "java/lang/IncompatibleClassChangeError";
123 char *string_java_lang_InternalError =
124 "java/lang/InternalError";
126 char *string_java_lang_LinkageError =
127 "java/lang/LinkageError";
129 char *string_java_lang_NoClassDefFoundError =
130 "java/lang/NoClassDefFoundError";
132 char *string_java_lang_NoSuchFieldError =
133 "java/lang/NoSuchFieldError";
135 char *string_java_lang_NoSuchMethodError =
136 "java/lang/NoSuchMethodError";
138 char *string_java_lang_OutOfMemoryError =
139 "java/lang/OutOfMemoryError";
142 void throw_exception() {}
143 void throw_exception_exit() {}
145 void throw_cacao_exception_exit(char *exception, char *message)
148 "Exception in thread \"main\" %s: %s\n", exception, message);
156 void new_exception(char *classname)
158 printf("Exception in thread \"main\" %s\n", classname);
162 void new_exception_message(char *classname, char *message)
164 printf("Exception in thread \"main\" %s: %s\n", classname, message);
168 void new_exception_throwable(char *classname, java_objectheader *t) {}
169 void new_exception_utfmessage(char *classname, utf *message)
171 printf("Exception in thread \"main\" %s: ", classname);
172 utf_display(message);
177 java_objectheader *literalstring_new(utf *u) { return NULL; }
180 void literalstring_free(java_objectheader *o) { }
181 void stringtable_update() { }
182 void synchronize_caches() { }
183 void asm_call_jit_compiler() { }
184 void asm_calljavafunction() { }
185 s4 asm_builtin_checkcast(java_objectheader *obj, classinfo *class) { return 0; }
187 s4 asm_builtin_idiv(s4 a, s4 b) {return 0;}
188 s4 asm_builtin_irem(s4 a, s4 b) {return 0;}
189 s8 asm_builtin_ldiv(s8 a, s8 b) {return 0;}
190 s8 asm_builtin_lrem(s8 a, s8 b) {return 0;}
192 s4 asm_builtin_f2i(float a) { return 0; }
193 s8 asm_builtin_f2l(float a) { return 0; }
194 s4 asm_builtin_d2i(double a) { return 0; }
195 s8 asm_builtin_d2l(double a) { return 0; }
197 void asm_builtin_monitorenter(java_objectheader *o) {}
198 void asm_builtin_monitorexit(java_objectheader *o) {}
200 s4 asm_builtin_checkarraycast(java_objectheader *obj, vftbl *target) {return 0;}
202 #if defined(__MIPS__)
203 void atomic_swap() {}
204 void compare_and_swap() {}
208 #if defined(__I386__)
209 s4 asm_builtin_arrayinstanceof(java_objectheader *obj, classinfo *class) { return 0; }
210 void asm_builtin_newarray(s4 size, vftbl *arrayvftbl) {}
213 void asm_builtin_aastore(java_objectarray *a, s4 index, java_objectheader *o) {}
215 u1 *createcompilerstub(methodinfo *m) {return NULL;}
216 u1 *createnativestub(functionptr f, methodinfo *m) {return NULL;}
217 u1 *oldcreatenativestub(functionptr f, methodinfo *m) {return NULL;}
219 void removecompilerstub(u1 *stub) {}
220 void removenativestub(u1 *stub) {}
222 void asm_perform_threadswitch(u1 **from, u1 **to, u1 **stackTop) {}
223 u1* asm_initialize_thread_stack(void *func, u1 *stack) { return NULL; }
224 void thread_restartcriticalsection() {}
225 void asm_switchstackandcall() {}
226 void asm_handle_builtin_exception(classinfo *c) {}
227 void asm_getclassvalues_atomic() {}
229 #if defined(__DARWIN__)
230 int cacao_catch_Handler() {}
233 #if defined(USE_THREADS) && defined(NATIVE_THREADS)
234 threadcritnode asm_criticalsections;
237 java_objectheader *native_new_and_init(void *p) { return NULL; }
240 /************************ global variables **********************/
242 THREADSPECIFIC java_objectheader *_exceptionptr;
244 static chain *nativemethod_chain; /* chain with native methods */
245 static chain *nativeclass_chain; /* chain with processed classes */
246 static chain *ident_chain; /* chain with method and field names in current class */
247 static FILE *file = NULL;
248 static u4 outputsize;
249 static bool dopadding;
252 static void printIDpart(int c)
254 if ((c >= 'a' && c <= 'z')
255 || (c >= 'A' && c <= 'Z')
256 || (c >= '0' && c <= '9')
264 static void printID(utf *u)
266 char *utf_ptr = u->text;
269 for (i = 0; i < utf_strlen(u); i++)
270 printIDpart(utf_nextu2(&utf_ptr));
274 static void addoutputsize (int len)
277 if (!dopadding) return;
279 newsize = ALIGN(outputsize, len);
281 for (i = outputsize; i < newsize; i++) fprintf(file, " u1 pad%d\n", (int) i);
282 outputsize = newsize;
285 static void printOverloadPart(utf *desc)
287 char *utf_ptr=desc->text;
291 while ((c=utf_nextu2(&utf_ptr))!=')') {
301 fprintf (file, "%c",(char)c);
308 while ( (c=utf_nextu2(&utf_ptr)) != ';')
314 default: panic ("invalid method descriptor");
319 static char *printtype(char *utf_ptr)
323 switch (utf_nextu2(&utf_ptr)) {
324 case 'V': fprintf (file, "void");
330 case 'Z': addoutputsize (4);
331 fprintf (file, "s4");
333 case 'J': addoutputsize (8);
334 fprintf (file, "s8");
336 case 'F': addoutputsize (4);
337 fprintf (file, "float");
339 case 'D': addoutputsize (8);
340 fprintf (file, "double");
343 addoutputsize ( sizeof(java_arrayheader*) );
344 switch (utf_nextu2(&utf_ptr)) {
345 case 'I': fprintf (file, "java_intarray*"); break;
346 case 'J': fprintf (file, "java_longarray*"); break;
347 case 'Z': fprintf (file, "java_booleanarray*"); break;
348 case 'B': fprintf (file, "java_bytearray*"); break;
349 case 'S': fprintf (file, "java_shortarray*"); break;
350 case 'C': fprintf (file, "java_chararray*"); break;
351 case 'F': fprintf (file, "java_floatarray*"); break;
352 case 'D': fprintf (file, "java_doublearray*"); break;
354 case '[': fprintf (file, "java_objectarray*");
355 while ((c = utf_nextu2(&utf_ptr)) == '[') ;
357 while (utf_nextu2(&utf_ptr) != ';');
360 case 'L': fprintf (file, "java_objectarray*");
361 while ( utf_nextu2(&utf_ptr) != ';');
363 default: panic ("invalid type descriptor");
368 addoutputsize ( sizeof(java_objectheader*));
369 fprintf (file, "struct ");
370 while ( (c = utf_nextu2(&utf_ptr)) != ';' ) printIDpart (c);
374 default: panic ("Unknown type in field descriptor");
381 /***** determine the number of entries of a utf string in the ident chain *****/
383 static int searchidentchain_utf(utf *ident)
385 utf *u = chain_first(ident_chain); /* first element of list */
389 if (u==ident) count++; /* string found */
390 u = chain_next(ident_chain); /* next element in list */
397 /************** print structure for direct access to objects ******************/
399 static void printfields(classinfo *c)
406 addoutputsize(sizeof(java_objectheader));
407 fprintf(file, " java_objectheader header;\n");
411 printfields(c->super);
413 for (i = 0; i < c->fieldscount; i++) {
416 if (!(f->flags & ACC_STATIC)) {
418 printtype(f->descriptor->text);
420 utf_fprint(file, f->name);
422 /* rename multiple fieldnames */
423 if ((ident_count = searchidentchain_utf(f->name)))
424 fprintf(file, "%d", ident_count - 1);
425 chain_addlast(ident_chain, f->name);
427 fprintf(file, ";\n");
433 /***************** store prototype for native method in file ******************/
435 static void printmethod(methodinfo *m)
441 /* search for return-type in descriptor */
442 utf_ptr = m->descriptor->text;
443 while (utf_nextu2(&utf_ptr) != ')');
446 fprintf(file, "\n/*\n * Class: ");
447 utf_fprint(file, m->class->name);
448 fprintf(file, "\n * Method: ");
449 utf_fprint(file, m->name);
450 fprintf(file, "\n * Signature: ");
451 utf_fprint(file, m->descriptor);
452 fprintf(file, "\n */\n");
454 /* create prototype */
455 fprintf(file, "JNIEXPORT ");
457 fprintf(file, " JNICALL Java_");
458 printID(m->class->name);
460 chain_addlast(ident_chain, m->name);
464 if (m->nativelyoverloaded) printOverloadPart(m->descriptor);
465 fprintf(file, "(JNIEnv *env");
467 utf_ptr = m->descriptor->text + 1;
469 if (!(m->flags & ACC_STATIC)) {
470 fprintf(file, ", struct ");
471 printID(m->class->name);
472 fprintf(file, "* this");
475 fprintf(file, ", jclass clazz");
478 if ((*utf_ptr) != ')') fprintf(file, ", ");
480 while ((*utf_ptr) != ')') {
481 utf_ptr = printtype(utf_ptr);
482 fprintf(file, " par%d", paramnum++);
483 if ((*utf_ptr)!=')') fprintf(file, ", ");
486 fprintf(file, ");\n\n");
490 /******* remove package-name in fully-qualified classname *********************/
492 static void gen_header_filename(char *buffer, utf *u)
496 for (i = 0;i < utf_strlen(u); i++) {
497 if ((u->text[i] == '/') || (u->text[i] == '$')) buffer[i] = '_'; /* convert '$' and '/' to '_' */
498 else buffer[i] = u->text[i];
500 buffer[utf_strlen(u)] = '\0';
504 /* create headerfile for classes and store native methods in chain ************/
506 static void headerfile_generate(classinfo *c)
508 char header_filename[1024] = "";
509 char classname[1024];
510 char uclassname[1024];
515 u2 nativelyoverloaded;
517 /* store class in chain */
518 chain_addlast(nativeclass_chain, c);
520 /* open headerfile for class */
521 gen_header_filename(classname, c->name);
523 /* create chain for renaming fields */
524 ident_chain = chain_new();
526 sprintf(header_filename, "nat/%s.h", classname);
527 file = fopen(header_filename, "w");
528 if (!file) panic("Can not open file to store header information");
530 fprintf(file, "/* This file is machine generated, don't edit it !*/\n\n");
532 /* convert to uppercase */
533 for (i = 0; classname[i]; i++) {
534 uclassname[i] = toupper(classname[i]);
536 uclassname[i] = '\0';
538 fprintf(file, "#ifndef _%s_H\n#define _%s_H\n\n", uclassname, uclassname);
540 /* create structure for direct access to objects */
541 fprintf(file, "/* Structure information for class: ");
542 utf_fprint(file, c->name);
543 fprintf(file, " */\n\n");
544 fprintf(file, "typedef struct ");
546 fprintf(file, " {\n");
554 fprintf(file, ";\n\n");
556 /* create chain for renaming overloaded methods */
557 chain_free(ident_chain);
558 ident_chain = chain_new();
560 /* create method-prototypes */
562 /* find overloaded methods */
563 for (i = 0; i < c->methodscount; i++) {
565 m = &(c->methods[i]);
567 if (!(m->flags & ACC_NATIVE)) continue;
568 if (!m->nativelyoverloaded) {
569 nativelyoverloaded=false;
570 for (i2=i+1;i2<c->methodscount; i2++) {
571 m2 = &(c->methods[i2]);
572 if (!(m2->flags & ACC_NATIVE)) continue;
573 if (m->name==m2->name) {
574 m2->nativelyoverloaded=true;
575 nativelyoverloaded=true;
578 m->nativelyoverloaded=nativelyoverloaded;
583 for (i = 0; i < c->methodscount; i++) {
585 m = &(c->methods[i]);
587 if (m->flags & ACC_NATIVE) {
588 chain_addlast(nativemethod_chain, m);
593 chain_free(ident_chain);
595 fprintf(file, "#endif\n\n");
601 /******** print classname, '$' used to seperate inner-class name ***********/
603 void print_classname(classinfo *clazz)
605 utf *u = clazz->name;
606 char *endpos = u->text + u->blength;
607 char *utf_ptr = u->text;
610 while (utf_ptr < endpos) {
611 if ((c = utf_nextu2(&utf_ptr)) == '_') {
621 /*************** create table for locating native functions ****************/
623 static void printnativetableentry(methodinfo *m)
625 fprintf(file, " { \"");
626 print_classname(m->class);
627 fprintf(file, "\",\n \"");
628 utf_fprint(file, m->name);
629 fprintf(file, "\",\n \"");
630 utf_fprint(file, m->descriptor);
631 fprintf(file, "\",\n ");
633 if ((m->flags & ACC_STATIC) != 0)
634 fprintf(file, "true");
636 fprintf(file, "false");
638 fprintf(file, ",\n ");
639 fprintf(file, "(functionptr) Java_");
640 printID(m->class->name);
643 if (m->nativelyoverloaded) printOverloadPart(m->descriptor);
644 fprintf(file,"\n },\n");
648 /***************************************************************************
650 create the nativetypes-headerfile which includes
651 the headerfiles of the classes stored in the classes-chain
653 ****************************************************************************/
655 static void headers_finish()
659 char classname[1024];
661 file = fopen("nativetypes.hh", "w");
664 panic("Can not open file 'native.h' to store header information");
666 fprintf(file, "/* Headerfile for native methods: nativetypes.hh */\n");
667 fprintf(file, "/* This file is machine generated, don't edit it !*/\n\n");
668 fprintf(file, "\n/* include native-Headerfiles */\n\n");
670 c = chain_first(nativeclass_chain);
673 gen_header_filename(classname, c->name);
674 fprintf(file, "#include \"nat/%s.h\"\n", classname);
675 c = chain_next(nativeclass_chain);
679 chain_free(nativeclass_chain);
681 /* create table of native-methods */
683 file = fopen("nativetable.hh", "w");
686 panic("Can not open file 'nativetable' to store native-link-table");
688 fprintf(file, "/* Table of native methods: nativetables.hh */\n");
689 fprintf(file, "/* This file is machine generated, don't edit it !*/\n\n");
691 while ((m = chain_first(nativemethod_chain)) != NULL) {
692 chain_remove(nativemethod_chain);
693 printnativetableentry(m);
696 chain_free(nativemethod_chain);
701 /******************** internal function: print_usage ************************
703 Prints usage information for the JAVA header generator to stdout.
705 ***************************************************************************/
707 static void print_usage()
709 printf("Usage: cacaoh class [class..]\n");
714 /************************** Function: main *******************************
718 **************************************************************************/
720 int main(int argc, char **argv)
727 /********** internal (only used by main) *****************************/
729 char classpath[500] = "";
730 char offsets_filename[1024] = ""; /* phil */
731 u4 heapmaxsize = 2 * 1024 * 1024;
732 u4 heapstartsize = 100 * 1024;
734 /*********** options so only headers are generated *******************/
736 makeinitializations = false;
739 /************ Collect some info from the environment *****************/
741 cp = getenv("CLASSPATH");
743 strcpy(classpath + strlen(classpath), ":");
744 strcpy(classpath + strlen(classpath), cp);
753 /**************************** Program start **************************/
756 log_text("Java - header-generator started");
758 sprintf(offsets_filename, "jit/%s/offsets.h", ARCH_DIR);
759 file = fopen(offsets_filename, "w");
761 fprintf(stderr, "Can not open file '%s' for write", offsets_filename);
765 fprintf(file, "/* This file is machine generated, don't edit it !*/\n\n");
767 fprintf(file, "#define offobjvftbl %3d\n", (int) OFFSET(java_objectheader, vftbl));
768 fprintf(file, "#define offarraysize %3d\n", (int) OFFSET(java_arrayheader, size));
769 fprintf(file, "#define offobjarrdata %3d\n\n", (int) OFFSET(java_objectarray, data[0]));
770 fprintf(file, "#define offbaseval %3d\n", (int) OFFSET(vftbl, baseval));
771 fprintf(file, "#define offdiffval %3d\n\n", (int) OFFSET(vftbl, diffval));
772 fprintf(file, "#define offclass %3d\n\n", (int) OFFSET(vftbl, class));
774 fprintf(file, "#define offclassvftbl %3d\n", (int) OFFSET(classinfo, vftbl));
775 fprintf(file, "#define offclassinit %3d\n", (int) OFFSET(classinfo, initialized));
776 fprintf(file, "#define offclassloaded %3d\n", (int) OFFSET(classinfo, loaded));
777 fprintf(file, "#define offclasslinked %3d\n\n", (int) OFFSET(classinfo, linked));
779 fprintf(file, "#define offjniitemtype %3d\n", (int) OFFSET(jni_callblock, itemtype));
780 fprintf(file, "#define offjniitem %3d\n", (int) OFFSET(jni_callblock, item));
781 fprintf(file, "#define sizejniblock %3d\n\n", (int) sizeof(jni_callblock));
783 fprintf(file, "#define offclassmethodinfo %3d\n\n", (int) OFFSET(methodinfo,class));
785 fprintf(file, "#define offmethodnative %3d\n", (int) OFFSET(native_stackframeinfo,method));
786 /* fprintf(file, "#define offreturnfromnative %3d\n", (int) OFFSET(native_stackframeinfo,returnFromNative));
787 fprintf(file, "#define offaddrreturnfromnative %3d\n", (int) OFFSET(native_stackframeinfo,addrReturnFromNative));
788 fprintf(file, "#define offprevnative %3d\n", (int) OFFSET(native_stackframeinfo,prev));
789 fprintf(file, "#define offnextnative %3d\n", (int) OFFSET(native_stackframeinfo,next));*/
792 fprintf(file, "#define offcast_super_baseval %3d\n", (int) OFFSET(castinfo, super_baseval));
793 fprintf(file, "#define offcast_super_diffval %3d\n", (int) OFFSET(castinfo, super_diffval));
794 fprintf(file, "#define offcast_sub_baseval %3d\n", (int) OFFSET(castinfo, sub_baseval));
798 /* initialize the garbage collector */
799 gc_init(heapmaxsize, heapstartsize);
801 suck_init(classpath);
805 #if defined(USE_THREADS) && defined(NATIVE_THREADS)
811 /*********************** Load JAVA classes **************************/
813 nativemethod_chain = chain_new();
814 nativeclass_chain = chain_new();
816 for (a = 1; a < argc; a++) {
819 /* convert classname */
820 for (i = strlen(cp) - 1; i >= 0; i--) {
828 /* topclass = loader_load(utf_new_char(cp)); */
829 topclass = class_load(class_new(utf_new_char(cp)));
830 class_link(topclass);
832 headerfile_generate(topclass);
837 /************************ Release all resources **********************/
840 tables_close(literalstring_free);
842 /* Print "finished" message */
844 log_text("Java - header-generator stopped");
852 void setVMClassField(classinfo *c)
857 void *Java_java_lang_VMObject_clone(void *env, void *clazz, void * this) {
863 * These are local overrides for various environment variables in Emacs.
864 * Please do not remove this and leave it at the end of the file, where
865 * Emacs will automagically detect them.
866 * ---------------------------------------------------------------------
869 * indent-tabs-mode: t