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 1216 2004-06-29 13:31:58Z 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 utf *javastring_toutf(java_lang_String *string, bool isclassname)
95 /* some exception stuff */
97 char *string_java_lang_IllegalMonitorStateException =
98 "java/lang/IllegalMonitorStateException";
100 char *string_java_lang_NegativeArraySizeException =
101 "java/lang/NegativeArraySizeException";
104 char *string_java_lang_AbstractMethodError =
105 "java/lang/AbstractMethodError";
107 char *string_java_lang_ClassCircularityError =
108 "java/lang/ClassCircularityError";
110 char *string_java_lang_ClassFormatError =
111 "java/lang/ClassFormatError";
113 char *string_java_lang_ExceptionInInitializerError =
114 "java/lang/ExceptionInInitializerError";
116 char *string_java_lang_IncompatibleClassChangeError =
117 "java/lang/IncompatibleClassChangeError";
119 char *string_java_lang_InternalError =
120 "java/lang/InternalError";
122 char *string_java_lang_LinkageError =
123 "java/lang/LinkageError";
125 char *string_java_lang_NoClassDefFoundError =
126 "java/lang/NoClassDefFoundError";
128 char *string_java_lang_NoSuchFieldError =
129 "java/lang/NoSuchFieldError";
131 char *string_java_lang_NoSuchMethodError =
132 "java/lang/NoSuchMethodError";
134 char *string_java_lang_OutOfMemoryError =
135 "java/lang/OutOfMemoryError";
138 void throw_exception() {}
139 void throw_exception_exit() {}
141 void throw_cacao_exception_exit(char *exception, char *message)
144 "Exception in thread \"main\" %s: %s\n", exception, message);
152 void new_exception(char *classname)
154 printf("Exception in thread \"main\" %s\n", classname);
158 void new_exception_message(char *classname, char *message)
160 printf("Exception in thread \"main\" %s: %s\n", classname, message);
164 void new_exception_throwable(char *classname, java_objectheader *t) {}
165 void new_exception_utfmessage(char *classname, utf *message)
167 printf("Exception in thread \"main\" %s: ", classname);
168 utf_display(message);
173 java_objectheader *literalstring_new(utf *u) { return NULL; }
176 void literalstring_free(java_objectheader *o) { }
177 void stringtable_update() { }
178 void synchronize_caches() { }
179 void asm_call_jit_compiler() { }
180 void asm_calljavafunction() { }
181 s4 asm_builtin_checkcast(java_objectheader *obj, classinfo *class) { return 0; }
183 s4 asm_builtin_idiv(s4 a, s4 b) {return 0;}
184 s4 asm_builtin_irem(s4 a, s4 b) {return 0;}
185 s8 asm_builtin_ldiv(s8 a, s8 b) {return 0;}
186 s8 asm_builtin_lrem(s8 a, s8 b) {return 0;}
188 s4 asm_builtin_f2i(float a) { return 0; }
189 s8 asm_builtin_f2l(float a) { return 0; }
190 s4 asm_builtin_d2i(double a) { return 0; }
191 s8 asm_builtin_d2l(double a) { return 0; }
193 void asm_builtin_monitorenter(java_objectheader *o) {}
194 void asm_builtin_monitorexit(java_objectheader *o) {}
196 s4 asm_builtin_checkarraycast(java_objectheader *obj, vftbl *target) {return 0;}
198 #if defined(__MIPS__)
199 void atomic_swap() {}
200 void compare_and_swap() {}
204 #if defined(__I386__)
205 s4 asm_builtin_arrayinstanceof(java_objectheader *obj, classinfo *class) { return 0; }
206 void asm_builtin_newarray(s4 size, vftbl *arrayvftbl) {}
209 void asm_builtin_aastore(java_objectarray *a, s4 index, java_objectheader *o) {}
211 u1 *createcompilerstub(methodinfo *m) {return NULL;}
212 u1 *createnativestub(functionptr f, methodinfo *m) {return NULL;}
213 u1 *oldcreatenativestub(functionptr f, methodinfo *m) {return NULL;}
215 void removecompilerstub(u1 *stub) {}
216 void removenativestub(u1 *stub) {}
218 void asm_perform_threadswitch(u1 **from, u1 **to, u1 **stackTop) {}
219 u1* asm_initialize_thread_stack(void *func, u1 *stack) { return NULL; }
220 void thread_restartcriticalsection() {}
221 void asm_switchstackandcall() {}
222 void asm_handle_builtin_exception(classinfo *c) {}
223 void asm_getclassvalues_atomic() {}
225 #if defined(__DARWIN__)
226 int cacao_catch_Handler() {}
229 #if defined(USE_THREADS) && defined(NATIVE_THREADS)
230 threadcritnode asm_criticalsections;
233 java_objectheader *native_new_and_init(void *p) { return NULL; }
236 /************************ global variables **********************/
238 THREADSPECIFIC java_objectheader *_exceptionptr;
240 static chain *nativemethod_chain; /* chain with native methods */
241 static chain *nativeclass_chain; /* chain with processed classes */
242 static chain *ident_chain; /* chain with method and field names in current class */
243 static FILE *file = NULL;
244 static u4 outputsize;
245 static bool dopadding;
248 static void printIDpart(int c)
250 if ((c >= 'a' && c <= 'z')
251 || (c >= 'A' && c <= 'Z')
252 || (c >= '0' && c <= '9')
260 static void printID(utf *u)
262 char *utf_ptr = u->text;
265 for (i = 0; i < utf_strlen(u); i++)
266 printIDpart(utf_nextu2(&utf_ptr));
270 static void addoutputsize (int len)
273 if (!dopadding) return;
275 newsize = ALIGN(outputsize, len);
277 for (i = outputsize; i < newsize; i++) fprintf(file, " u1 pad%d\n", (int) i);
278 outputsize = newsize;
281 static void printOverloadPart(utf *desc)
283 char *utf_ptr=desc->text;
287 while ((c=utf_nextu2(&utf_ptr))!=')') {
297 fprintf (file, "%c",(char)c);
304 while ( (c=utf_nextu2(&utf_ptr)) != ';')
310 default: panic ("invalid method descriptor");
315 static char *printtype(char *utf_ptr)
319 switch (utf_nextu2(&utf_ptr)) {
320 case 'V': fprintf (file, "void");
326 case 'Z': addoutputsize (4);
327 fprintf (file, "s4");
329 case 'J': addoutputsize (8);
330 fprintf (file, "s8");
332 case 'F': addoutputsize (4);
333 fprintf (file, "float");
335 case 'D': addoutputsize (8);
336 fprintf (file, "double");
339 addoutputsize ( sizeof(java_arrayheader*) );
340 switch (utf_nextu2(&utf_ptr)) {
341 case 'I': fprintf (file, "java_intarray*"); break;
342 case 'J': fprintf (file, "java_longarray*"); break;
343 case 'Z': fprintf (file, "java_booleanarray*"); break;
344 case 'B': fprintf (file, "java_bytearray*"); break;
345 case 'S': fprintf (file, "java_shortarray*"); break;
346 case 'C': fprintf (file, "java_chararray*"); break;
347 case 'F': fprintf (file, "java_floatarray*"); break;
348 case 'D': fprintf (file, "java_doublearray*"); break;
350 case '[': fprintf (file, "java_objectarray*");
351 while ((c = utf_nextu2(&utf_ptr)) == '[') ;
353 while (utf_nextu2(&utf_ptr) != ';');
356 case 'L': fprintf (file, "java_objectarray*");
357 while ( utf_nextu2(&utf_ptr) != ';');
359 default: panic ("invalid type descriptor");
364 addoutputsize ( sizeof(java_objectheader*));
365 fprintf (file, "struct ");
366 while ( (c = utf_nextu2(&utf_ptr)) != ';' ) printIDpart (c);
370 default: panic ("Unknown type in field descriptor");
377 /***** determine the number of entries of a utf string in the ident chain *****/
379 static int searchidentchain_utf(utf *ident)
381 utf *u = chain_first(ident_chain); /* first element of list */
385 if (u==ident) count++; /* string found */
386 u = chain_next(ident_chain); /* next element in list */
393 /************** print structure for direct access to objects ******************/
395 static void printfields(classinfo *c)
402 addoutputsize(sizeof(java_objectheader));
403 fprintf(file, " java_objectheader header;\n");
407 printfields(c->super);
409 for (i = 0; i < c->fieldscount; i++) {
412 if (!(f->flags & ACC_STATIC)) {
414 printtype(f->descriptor->text);
416 utf_fprint(file, f->name);
418 /* rename multiple fieldnames */
419 if ((ident_count = searchidentchain_utf(f->name)))
420 fprintf(file, "%d", ident_count - 1);
421 chain_addlast(ident_chain, f->name);
423 fprintf(file, ";\n");
429 /***************** store prototype for native method in file ******************/
431 static void printmethod(methodinfo *m)
437 /* search for return-type in descriptor */
438 utf_ptr = m->descriptor->text;
439 while (utf_nextu2(&utf_ptr) != ')');
442 fprintf(file, "\n/*\n * Class: ");
443 utf_fprint(file, m->class->name);
444 fprintf(file, "\n * Method: ");
445 utf_fprint(file, m->name);
446 fprintf(file, "\n * Signature: ");
447 utf_fprint(file, m->descriptor);
448 fprintf(file, "\n */\n");
450 /* create prototype */
451 fprintf(file, "JNIEXPORT ");
453 fprintf(file, " JNICALL Java_");
454 printID(m->class->name);
456 chain_addlast(ident_chain, m->name);
460 if (m->nativelyoverloaded) printOverloadPart(m->descriptor);
461 fprintf(file, "(JNIEnv *env");
463 utf_ptr = m->descriptor->text + 1;
465 if (!(m->flags & ACC_STATIC)) {
466 fprintf(file, ", struct ");
467 printID(m->class->name);
468 fprintf(file, "* this");
471 fprintf(file, ", jclass clazz");
474 if ((*utf_ptr) != ')') fprintf(file, ", ");
476 while ((*utf_ptr) != ')') {
477 utf_ptr = printtype(utf_ptr);
478 fprintf(file, " par%d", paramnum++);
479 if ((*utf_ptr)!=')') fprintf(file, ", ");
482 fprintf(file, ");\n\n");
486 /******* remove package-name in fully-qualified classname *********************/
488 static void gen_header_filename(char *buffer, utf *u)
492 for (i = 0;i < utf_strlen(u); i++) {
493 if ((u->text[i] == '/') || (u->text[i] == '$')) buffer[i] = '_'; /* convert '$' and '/' to '_' */
494 else buffer[i] = u->text[i];
496 buffer[utf_strlen(u)] = '\0';
500 /* create headerfile for classes and store native methods in chain ************/
502 static void headerfile_generate(classinfo *c)
504 char header_filename[1024] = "";
505 char classname[1024];
506 char uclassname[1024];
511 u2 nativelyoverloaded;
513 /* store class in chain */
514 chain_addlast(nativeclass_chain, c);
516 /* open headerfile for class */
517 gen_header_filename(classname, c->name);
519 /* create chain for renaming fields */
520 ident_chain = chain_new();
522 sprintf(header_filename, "nat/%s.h", classname);
523 file = fopen(header_filename, "w");
524 if (!file) panic("Can not open file to store header information");
526 fprintf(file, "/* This file is machine generated, don't edit it !*/\n\n");
528 /* convert to uppercase */
529 for (i = 0; classname[i]; i++) {
530 uclassname[i] = toupper(classname[i]);
532 uclassname[i] = '\0';
534 fprintf(file, "#ifndef _%s_H\n#define _%s_H\n\n", uclassname, uclassname);
536 /* create structure for direct access to objects */
537 fprintf(file, "/* Structure information for class: ");
538 utf_fprint(file, c->name);
539 fprintf(file, " */\n\n");
540 fprintf(file, "typedef struct ");
542 fprintf(file, " {\n");
550 fprintf(file, ";\n\n");
552 /* create chain for renaming overloaded methods */
553 chain_free(ident_chain);
554 ident_chain = chain_new();
556 /* create method-prototypes */
558 /* find overloaded methods */
559 for (i = 0; i < c->methodscount; i++) {
561 m = &(c->methods[i]);
563 if (!(m->flags & ACC_NATIVE)) continue;
564 if (!m->nativelyoverloaded) {
565 nativelyoverloaded=false;
566 for (i2=i+1;i2<c->methodscount; i2++) {
567 m2 = &(c->methods[i2]);
568 if (!(m2->flags & ACC_NATIVE)) continue;
569 if (m->name==m2->name) {
570 m2->nativelyoverloaded=true;
571 nativelyoverloaded=true;
574 m->nativelyoverloaded=nativelyoverloaded;
579 for (i = 0; i < c->methodscount; i++) {
581 m = &(c->methods[i]);
583 if (m->flags & ACC_NATIVE) {
584 chain_addlast(nativemethod_chain, m);
589 chain_free(ident_chain);
591 fprintf(file, "#endif\n\n");
597 /******** print classname, '$' used to seperate inner-class name ***********/
599 void print_classname(classinfo *clazz)
601 utf *u = clazz->name;
602 char *endpos = u->text + u->blength;
603 char *utf_ptr = u->text;
606 while (utf_ptr < endpos) {
607 if ((c = utf_nextu2(&utf_ptr)) == '_') {
617 /*************** create table for locating native functions ****************/
619 static void printnativetableentry(methodinfo *m)
621 fprintf(file, " { \"");
622 print_classname(m->class);
623 fprintf(file, "\",\n \"");
624 utf_fprint(file, m->name);
625 fprintf(file, "\",\n \"");
626 utf_fprint(file, m->descriptor);
627 fprintf(file, "\",\n ");
629 if ((m->flags & ACC_STATIC) != 0)
630 fprintf(file, "true");
632 fprintf(file, "false");
634 fprintf(file, ",\n ");
635 fprintf(file, "(functionptr) Java_");
636 printID(m->class->name);
639 if (m->nativelyoverloaded) printOverloadPart(m->descriptor);
640 fprintf(file,"\n },\n");
644 /***************************************************************************
646 create the nativetypes-headerfile which includes
647 the headerfiles of the classes stored in the classes-chain
649 ****************************************************************************/
651 static void headers_finish()
655 char classname[1024];
657 file = fopen("nativetypes.hh", "w");
660 panic("Can not open file 'native.h' to store header information");
662 fprintf(file, "/* Headerfile for native methods: nativetypes.hh */\n");
663 fprintf(file, "/* This file is machine generated, don't edit it !*/\n\n");
664 fprintf(file, "\n/* include native-Headerfiles */\n\n");
666 c = chain_first(nativeclass_chain);
669 gen_header_filename(classname, c->name);
670 fprintf(file, "#include \"nat/%s.h\"\n", classname);
671 c = chain_next(nativeclass_chain);
675 chain_free(nativeclass_chain);
677 /* create table of native-methods */
679 file = fopen("nativetable.hh", "w");
682 panic("Can not open file 'nativetable' to store native-link-table");
684 fprintf(file, "/* Table of native methods: nativetables.hh */\n");
685 fprintf(file, "/* This file is machine generated, don't edit it !*/\n\n");
687 while ((m = chain_first(nativemethod_chain)) != NULL) {
688 chain_remove(nativemethod_chain);
689 printnativetableentry(m);
692 chain_free(nativemethod_chain);
697 /******************** internal function: print_usage ************************
699 Prints usage information for the JAVA header generator to stdout.
701 ***************************************************************************/
703 static void print_usage()
705 printf("Usage: cacaoh class [class..]\n");
710 /************************** Function: main *******************************
714 **************************************************************************/
716 int main(int argc, char **argv)
723 /********** internal (only used by main) *****************************/
725 char classpath[500] = "";
726 char offsets_filename[1024] = ""; /* phil */
727 u4 heapmaxsize = 2 * 1024 * 1024;
728 u4 heapstartsize = 100 * 1024;
730 /*********** options so only headers are generated *******************/
732 makeinitializations = false;
735 /************ Collect some info from the environment *****************/
737 cp = getenv("CLASSPATH");
739 strcpy(classpath + strlen(classpath), ":");
740 strcpy(classpath + strlen(classpath), cp);
749 /**************************** Program start **************************/
752 log_text("Java - header-generator started");
754 sprintf(offsets_filename, "jit/%s/offsets.h", ARCH_DIR);
755 file = fopen(offsets_filename, "w");
757 fprintf(stderr, "Can not open file '%s' for write", offsets_filename);
761 fprintf(file, "/* This file is machine generated, don't edit it !*/\n\n");
763 fprintf(file, "#define offobjvftbl %3d\n", (int) OFFSET(java_objectheader, vftbl));
764 fprintf(file, "#define offarraysize %3d\n", (int) OFFSET(java_arrayheader, size));
765 fprintf(file, "#define offobjarrdata %3d\n\n", (int) OFFSET(java_objectarray, data[0]));
766 fprintf(file, "#define offbaseval %3d\n", (int) OFFSET(vftbl, baseval));
767 fprintf(file, "#define offdiffval %3d\n\n", (int) OFFSET(vftbl, diffval));
768 fprintf(file, "#define offclass %3d\n\n", (int) OFFSET(vftbl, class));
770 fprintf(file, "#define offclassvftbl %3d\n", (int) OFFSET(classinfo, vftbl));
771 fprintf(file, "#define offclassinit %3d\n", (int) OFFSET(classinfo, initialized));
772 fprintf(file, "#define offclassloaded %3d\n", (int) OFFSET(classinfo, loaded));
773 fprintf(file, "#define offclasslinked %3d\n\n", (int) OFFSET(classinfo, linked));
775 fprintf(file, "#define offjniitemtype %3d\n", (int) OFFSET(jni_callblock, itemtype));
776 fprintf(file, "#define offjniitem %3d\n", (int) OFFSET(jni_callblock, item));
777 fprintf(file, "#define sizejniblock %3d\n\n", (int) sizeof(jni_callblock));
779 fprintf(file, "#define offclassmethodinfo %3d\n\n", (int) OFFSET(methodinfo,class));
781 fprintf(file, "#define offmethodnative %3d\n", (int) OFFSET(native_stackframeinfo,method));
782 /* fprintf(file, "#define offreturnfromnative %3d\n", (int) OFFSET(native_stackframeinfo,returnFromNative));
783 fprintf(file, "#define offaddrreturnfromnative %3d\n", (int) OFFSET(native_stackframeinfo,addrReturnFromNative));
784 fprintf(file, "#define offprevnative %3d\n", (int) OFFSET(native_stackframeinfo,prev));
785 fprintf(file, "#define offnextnative %3d\n", (int) OFFSET(native_stackframeinfo,next));*/
788 fprintf(file, "#define offcast_super_baseval %3d\n", (int) OFFSET(castinfo, super_baseval));
789 fprintf(file, "#define offcast_super_diffval %3d\n", (int) OFFSET(castinfo, super_diffval));
790 fprintf(file, "#define offcast_sub_baseval %3d\n", (int) OFFSET(castinfo, sub_baseval));
794 /* initialize the garbage collector */
795 gc_init(heapmaxsize, heapstartsize);
797 suck_init(classpath);
801 #if defined(USE_THREADS) && defined(NATIVE_THREADS)
807 /*********************** Load JAVA classes **************************/
809 nativemethod_chain = chain_new();
810 nativeclass_chain = chain_new();
812 for (a = 1; a < argc; a++) {
815 /* convert classname */
816 for (i = strlen(cp) - 1; i >= 0; i--) {
824 /* topclass = loader_load(utf_new_char(cp)); */
825 topclass = class_load(class_new(utf_new_char(cp)));
826 class_link(topclass);
828 headerfile_generate(topclass);
833 /************************ Release all resources **********************/
836 tables_close(literalstring_free);
838 /* Print "finished" message */
840 log_text("Java - header-generator stopped");
848 void setVMClassField(classinfo *c)
853 void *Java_java_lang_VMObject_clone(void *env, void *clazz, void * this) {
859 * These are local overrides for various environment variables in Emacs.
860 * Please do not remove this and leave it at the end of the file, where
861 * Emacs will automagically detect them.
862 * ---------------------------------------------------------------------
865 * indent-tabs-mode: t