X-Git-Url: http://wien.tomnetworks.com/gitweb/?a=blobdiff_plain;f=src%2Fvm%2Floader.c;h=92d8c0fa395bda9fd3d6888de431d3c57d7e7038;hb=4f021ace4cbb48cb8d75e5445929a01f61ca756a;hp=08af5051e9369cc14e9594b51da8088b5dc04e2a;hpb=71397a3202d7021c52efa7f00f6b86fa5090ae70;p=cacao.git diff --git a/src/vm/loader.c b/src/vm/loader.c index 08af5051e..92d8c0fa3 100644 --- a/src/vm/loader.c +++ b/src/vm/loader.c @@ -1,9 +1,9 @@ -/* loader.c - class loader functions +/* src/vm/loader.c - class loader functions - Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003 - R. Grafl, A. Krall, C. Kruegel, C. Oates, R. Obermaisser, - M. Probst, S. Ring, E. Steiner, C. Thalinger, D. Thuernbeck, - P. Tomsich, J. Wenninger + Copyright (C) 1996-2005 R. Grafl, A. Krall, C. Kruegel, C. Oates, + R. Obermaisser, M. Platter, M. Probst, S. Ring, E. Steiner, + C. Thalinger, D. Thuernbeck, P. Tomsich, C. Ullrich, J. Wenninger, + Institut f. Computersprachen - TU Wien This file is part of CACAO. @@ -25,164 +25,231 @@ Contact: cacao@complang.tuwien.ac.at Authors: Reinhard Grafl + Changes: Andreas Krall Roman Obermaiser Mark Probst - Edwin Steiner + Edwin Steiner + Christian Thalinger - $Id: loader.c 951 2004-03-11 17:30:03Z jowenn $ + $Id: loader.c 3684 2005-11-16 13:28:33Z twisti $ */ - #include #include #include #include -#include "global.h" -#include "loader.h" -#include "main.h" -#include "native.h" -#include "tables.h" -#include "builtin.h" -#include "jit.h" -#include "asmpart.h" -#include "toolbox/memory.h" -#include "toolbox/loging.h" -#include "threads/thread.h" -#include "threads/locks.h" -#include -#ifdef USE_ZLIB -#include "unzip.h" +#include "config.h" +#include "mm/memory.h" +#include "native/native.h" +#include "native/include/java_lang_Throwable.h" + +#if defined(USE_THREADS) +# if defined(NATIVE_THREADS) +# include "threads/native/threads.h" +# else +# include "threads/green/threads.h" +# include "threads/green/locks.h" +# endif +#endif + +#include "toolbox/logging.h" +#include "toolbox/util.h" +#include "vm/exceptions.h" +#include "vm/builtin.h" +#include "vm/global.h" +#include "vm/linker.h" +#include "vm/loader.h" +#include "vm/options.h" +#include "vm/statistics.h" +#include "vm/stringlocal.h" +#include "vm/tables.h" +#include "vm/classcache.h" + +#if defined(USE_ZLIB) +# include "vm/unzip.h" +#endif + +#include "vm/jit/asmpart.h" +#include "vm/jit/codegen.inc.h" + +/******************************************************************************/ +/* DEBUG HELPERS */ +/******************************************************************************/ + +/*#define LOADER_VERBOSE*/ + +#ifndef NDEBUG +#define LOADER_DEBUG +#endif + +#ifdef LOADER_DEBUG +#define LOADER_ASSERT(cond) assert(cond) +#else +#define LOADER_ASSERT(cond) #endif #undef JOWENN_DEBUG #undef JOWENN_DEBUG1 #undef JOWENN_DEBUG2 -/* global variables ***********************************************************/ +#ifdef LOADER_VERBOSE +static int loader_recursion = 0; +#define LOADER_INDENT(str) do { int i; for(i=0;i */ -static utf *utf_clinit; /* */ -static utf *utf_initsystemclass; /* initializeSystemClass */ -static utf *utf_systemclass; /* java/lang/System */ -static utf *utf_vmclassloader; /* java/lang/VMClassLoader */ -static utf *utf_vmclass; /* java/lang/VMClassLoader */ -static utf *utf_initialize; -static utf *utf_initializedesc; -static utf *utf_java_lang_Object; /* java/lang/Object */ + /* Initialize the monitor pointer for zip/jar file locking. */ + for (cpi = classpath_entries; cpi != NULL; cpi = cpi->next) { + if (cpi->type == CLASSPATH_ARCHIVE) + initObjectLock(&cpi->header); + } +#endif + /* load some important classes */ + if (!(class_java_lang_Object = load_class_bootstrap(utf_java_lang_Object))) + return false; -utf* clinit_desc(){ - return utf_fidesc; -} -utf* clinit_name(){ - return utf_clinit; -} + if (!(class_java_lang_String = load_class_bootstrap(utf_java_lang_String))) + return false; + if (!(class_java_lang_Cloneable = + load_class_bootstrap(utf_java_lang_Cloneable))) + return false; -/* important system classes ***************************************************/ + if (!(class_java_io_Serializable = + load_class_bootstrap(utf_java_io_Serializable))) + return false; -classinfo *class_java_lang_Object; -classinfo *class_java_lang_String; -classinfo *class_java_lang_Throwable; -classinfo *class_java_lang_Cloneable; -classinfo *class_java_io_Serializable; + /* load classes for wrapping primitive types */ -/* Pseudo classes for the typechecker */ -classinfo *pseudo_class_Arraystub = NULL; -classinfo *pseudo_class_Null = NULL; -classinfo *pseudo_class_New = NULL; -vftbl *pseudo_class_Arraystub_vftbl = NULL; + if (!(class_java_lang_Void = load_class_bootstrap(utf_java_lang_Void))) + return false; -/* stefan */ -/* These are made static so they cannot be used for throwing in native */ -/* functions. */ -static classinfo *class_java_lang_ClassCastException; -static classinfo *class_java_lang_NullPointerException; -static classinfo *class_java_lang_ArrayIndexOutOfBoundsException; -static classinfo *class_java_lang_NegativeArraySizeException; -static classinfo *class_java_lang_OutOfMemoryError; -static classinfo *class_java_lang_ArithmeticException; -static classinfo *class_java_lang_ArrayStoreException; -static classinfo *class_java_lang_ThreadDeath; + if (!(class_java_lang_Boolean = + load_class_bootstrap(utf_java_lang_Boolean))) + return false; -utf *array_packagename = NULL; + if (!(class_java_lang_Byte = load_class_bootstrap(utf_java_lang_Byte))) + return false; -static int loader_inited = 0; + if (!(class_java_lang_Character = + load_class_bootstrap(utf_java_lang_Character))) + return false; + if (!(class_java_lang_Short = load_class_bootstrap(utf_java_lang_Short))) + return false; -/******************************************************************** - list of classpath entries (either filesystem directories or - ZIP/JAR archives -********************************************************************/ -static classpath_info *classpath_entries=0; + if (!(class_java_lang_Integer = + load_class_bootstrap(utf_java_lang_Integer))) + return false; + if (!(class_java_lang_Long = load_class_bootstrap(utf_java_lang_Long))) + return false; -/****************************************************************************** + if (!(class_java_lang_Float = load_class_bootstrap(utf_java_lang_Float))) + return false; - structure for primitive classes: contains the class for wrapping the - primitive type, the primitive class, the name of the class for wrapping, - the one character type signature and the name of the primitive class - - ******************************************************************************/ + if (!(class_java_lang_Double = load_class_bootstrap(utf_java_lang_Double))) + return false; + + + /* load some other important classes */ + + if (!(class_java_lang_Class = load_class_bootstrap(utf_java_lang_Class))) + return false; + + if (!(class_java_lang_ClassLoader = + load_class_bootstrap(utf_java_lang_ClassLoader))) + return false; + + if (!(class_java_lang_SecurityManager = + load_class_bootstrap(utf_java_lang_SecurityManager))) + return false; + + if (!(class_java_lang_System = load_class_bootstrap(utf_java_lang_System))) + return false; + + if (!(class_java_lang_Thread = + load_class_bootstrap(utf_new_char("java/lang/Thread")))) + return false; + + if (!(class_java_lang_ThreadGroup = + load_class_bootstrap(utf_java_lang_ThreadGroup))) + return false; + + if (!(class_java_lang_VMThread = + load_class_bootstrap(utf_new_char("java/lang/VMThread")))) + return false; + + + /* some classes which may be used more often */ + + if (!(class_java_lang_StackTraceElement = + load_class_bootstrap(utf_java_lang_StackTraceElement))) + return false; + + if (!(class_java_lang_reflect_Constructor = + load_class_bootstrap(utf_java_lang_reflect_Constructor))) + return false; + + if (!(class_java_lang_reflect_Field = + load_class_bootstrap(utf_java_lang_reflect_Field))) + return false; + + if (!(class_java_lang_reflect_Method = + load_class_bootstrap(utf_java_lang_reflect_Method))) + return false; + + if (!(class_java_security_PrivilegedAction = + load_class_bootstrap(utf_new_char("java/security/PrivilegedAction")))) + return false; + + if (!(class_java_util_Vector = load_class_bootstrap(utf_java_util_Vector))) + return false; + + if (!(arrayclass_java_lang_Object = + load_class_bootstrap(utf_new_char("[Ljava/lang/Object;")))) + return false; + +#if defined(USE_THREADS) + if (stackbottom != 0) + initLocks(); +#endif + + return true; +} -/* CAUTION: Don't change the order of the types. This table is indexed - * by the ARRAYTYPE_ constants (expcept ARRAYTYPE_OBJECT). - */ -primitivetypeinfo primitivetype_table[PRIMITIVETYPE_COUNT] = { - { NULL, NULL, "java/lang/Integer", 'I', "int" , "[I", NULL, NULL }, - { NULL, NULL, "java/lang/Long", 'J', "long" , "[J", NULL, NULL }, - { NULL, NULL, "java/lang/Float", 'F', "float" , "[F", NULL, NULL }, - { NULL, NULL, "java/lang/Double", 'D', "double" , "[D", NULL, NULL }, - { NULL, NULL, "java/lang/Byte", 'B', "byte" , "[B", NULL, NULL }, - { NULL, NULL, "java/lang/Character", 'C', "char" , "[C", NULL, NULL }, - { NULL, NULL, "java/lang/Short", 'S', "short" , "[S", NULL, NULL }, - { NULL, NULL, "java/lang/Boolean", 'Z', "boolean" , "[Z", NULL, NULL }, - { NULL, NULL, "java/lang/Void", 'V', "void" , NULL, NULL, NULL } -}; - - -/* instances of important system classes **************************************/ - -java_objectheader *proto_java_lang_ClassCastException; -java_objectheader *proto_java_lang_NullPointerException; -java_objectheader *proto_java_lang_ArrayIndexOutOfBoundsException; -java_objectheader *proto_java_lang_NegativeArraySizeException; -java_objectheader *proto_java_lang_OutOfMemoryError; -java_objectheader *proto_java_lang_ArithmeticException; -java_objectheader *proto_java_lang_ArrayStoreException; -java_objectheader *proto_java_lang_ThreadDeath; /************* functions for reading classdata ********************************* @@ -191,104 +258,156 @@ java_objectheader *proto_java_lang_ThreadDeath; *******************************************************************************/ -static char *classpath = ""; /* searchpath for classfiles */ -static u1 *classbuffer = NULL; /* pointer to buffer with classfile-data */ -static u1 *classbuf_pos; /* current position in classfile buffer */ -static int classbuffer_size; /* size of classfile-data */ +/* check_classbuffer_size ****************************************************** + + assert that at least bytes are left to read + is limited to the range of non-negative s4 values + +*******************************************************************************/ + +inline bool check_classbuffer_size(classbuffer *cb, s4 len) +{ + if (len < 0 || ((cb->data + cb->size) - cb->pos - 1) < len) { + *exceptionptr = + new_classformaterror((cb)->class, "Truncated class file"); + + return false; + } + + return true; +} + + +/* suck_nbytes ***************************************************************** + + transfer block of classfile data into a buffer + +*******************************************************************************/ + +inline void suck_nbytes(u1 *buffer, classbuffer *cb, s4 len) +{ + memcpy(buffer, cb->pos + 1, len); + cb->pos += len; +} + -/* assert that at least bytes are left to read */ -/* is limited to the range of non-negative s4 values */ -#define ASSERT_LEFT(len) \ - do {if ( ((s4)(len)) < 0 \ - || ((classbuffer + classbuffer_size) - classbuf_pos - 1) < (len)) \ - panic("Unexpected end of classfile"); } while(0) +/* skip_nbytes **************************************************************** -/* transfer block of classfile data into a buffer */ + skip block of classfile data -#define suck_nbytes(buffer,len) \ - do {ASSERT_LEFT(len); \ - memcpy(buffer,classbuf_pos+1,len); \ - classbuf_pos+=len;} while (0) +*******************************************************************************/ -/* skip block of classfile data */ +inline void skip_nbytes(classbuffer *cb, s4 len) +{ + cb->pos += len; +} -#define skip_nbytes(len) \ - do {ASSERT_LEFT(len); \ - classbuf_pos+=len;} while(0) -inline u1 suck_u1() +inline u1 suck_u1(classbuffer *cb) { - ASSERT_LEFT(1); - return *++classbuf_pos; + return *++(cb->pos); } -inline u2 suck_u2() + + +inline u2 suck_u2(classbuffer *cb) { - u1 a=suck_u1(), b=suck_u1(); - return ((u2)a<<8)+(u2)b; + u1 a = suck_u1(cb); + u1 b = suck_u1(cb); + return ((u2) a << 8) + (u2) b; } -inline u4 suck_u4() + + +inline u4 suck_u4(classbuffer *cb) { - u1 a=suck_u1(), b=suck_u1(), c=suck_u1(), d=suck_u1(); - return ((u4)a<<24)+((u4)b<<16)+((u4)c<<8)+(u4)d; + u1 a = suck_u1(cb); + u1 b = suck_u1(cb); + u1 c = suck_u1(cb); + u1 d = suck_u1(cb); + return ((u4) a << 24) + ((u4) b << 16) + ((u4) c << 8) + (u4) d; } -#define suck_s8() (s8) suck_u8() -#define suck_s2() (s2) suck_u2() -#define suck_s4() (s4) suck_u4() -#define suck_s1() (s1) suck_u1() /* get u8 from classfile data */ -static u8 suck_u8() +static u8 suck_u8(classbuffer *cb) { #if U8_AVAILABLE u8 lo, hi; - hi = suck_u4(); - lo = suck_u4(); + hi = suck_u4(cb); + lo = suck_u4(cb); return (hi << 32) + lo; #else u8 v; - v.high = suck_u4(); - v.low = suck_u4(); + v.high = suck_u4(cb); + v.low = suck_u4(cb); return v; #endif } /* get float from classfile data */ -static float suck_float() +static float suck_float(classbuffer *cb) { float f; #if !WORDS_BIGENDIAN - u1 buffer[4]; - u2 i; - for (i = 0; i < 4; i++) buffer[3 - i] = suck_u1(); - memcpy((u1*) (&f), buffer, 4); -#else - suck_nbytes((u1*) (&f), 4); + u1 buffer[4]; + u2 i; + + for (i = 0; i < 4; i++) + buffer[3 - i] = suck_u1(cb); + + memcpy((u1*) (&f), buffer, 4); +#else + suck_nbytes((u1*) (&f), cb, 4); #endif - PANICIF (sizeof(float) != 4, "Incompatible float-format"); + if (sizeof(float) != 4) { + *exceptionptr = new_internalerror("Incompatible float-format"); + + /* XXX should we exit in such a case? */ + throw_exception_exit(); + } return f; } /* get double from classfile data */ -static double suck_double() +static double suck_double(classbuffer *cb) { double d; #if !WORDS_BIGENDIAN - u1 buffer[8]; - u2 i; - for (i = 0; i < 8; i++) buffer[7 - i] = suck_u1 (); - memcpy((u1*) (&d), buffer, 8); + u1 buffer[8]; + u2 i; + +#if defined(__ARM__) && defined(__ARMEL__) && !defined(__VFP_FP__) + /* + * On little endian ARM processors when using FPA, word order + * of doubles is still big endian. So take that into account + * here. When using VFP, word order of doubles follows byte + * order. (michi 2005/07/24) + */ + for (i = 0; i < 4; i++) + buffer[3 - i] = suck_u1(cb); + for (i = 0; i < 4; i++) + buffer[7 - i] = suck_u1(cb); +#else + for (i = 0; i < 8; i++) + buffer[7 - i] = suck_u1(cb); +#endif /* defined(__ARM__) && ... */ + + memcpy((u1*) (&d), buffer, 8); #else - suck_nbytes((u1*) (&d), 8); + suck_nbytes((u1*) (&d), cb, 8); #endif - PANICIF (sizeof(double) != 8, "Incompatible double-format" ); + if (sizeof(double) != 8) { + *exceptionptr = new_internalerror("Incompatible double-format"); + + /* XXX should we exit in such a case? */ + throw_exception_exit(); + } return d; } @@ -300,215 +419,312 @@ static double suck_double() *******************************************************************************/ -void suck_init(char *cpath) +void suck_init(char *classpath) { - char *filename=0; - char *start; - char *end; - int isZip; - int filenamelen; - union classpath_info *tmp; - union classpath_info *insertAfter=0; - if (!cpath) return; - classpath = cpath; - classbuffer = NULL; - - if (classpath_entries) panic("suck_init should be called only once"); - for(start=classpath;(*start)!='\0';) { - for (end=start; ((*end)!='\0') && ((*end)!=':') ; end++); - if (start!=end) { - isZip=0; - filenamelen=(end-start); - if (filenamelen>3) { - if ( - ( - ( - ((*(end-1))=='p') || - ((*(end-1))=='P') - ) && - ( - ((*(end-2))=='i') || - ((*(end-2))=='I') - ) && - ( - ((*(end-3))=='z') || - ((*(end-3))=='Z') - ) - ) || - ( - ( - ((*(end-1))=='r') || - ((*(end-1))=='R') - ) && - ( - ((*(end-2))=='a') || - ((*(end-2))=='A') - ) && - ( - ((*(end-3))=='j') || - ((*(end-3))=='J') - ) - ) - ) isZip=1; -#if 0 - if ( - ( ( (*(end - 1)) == 'p') || ( (*(end - 1)) == 'P')) && - (((*(end - 2)) == 'i') || ( (*(end - 2)) == 'I'))) && - (( (*(end - 3)) == 'z') || ((*(end - 3)) == 'Z'))) - ) { - isZip=1; - } else if ( (( (*(end - 1)) == 'r') || ( (*(end - 1)) == 'R')) && - ((*(end - 2)) == 'a') || ( (*(end - 2)) == 'A')) && - (( (*(end - 3)) == 'j') || ((*(end - 3)) == 'J')) ) { - isZip=1; + char *start; + char *end; + char *filename; + s4 filenamelen; + bool is_zip; + classpath_info *cpi; + classpath_info *lastcpi; + char *cwd; + s4 cwdlen; + + /* search for last classpath entry (only if there already some) */ + + if ((lastcpi = classpath_entries)) { + while (lastcpi->next) + lastcpi = lastcpi->next; + } + + for (start = classpath; (*start) != '\0';) { + + /* search for ':' delimiter to get the end of the current entry */ + for (end = start; ((*end) != '\0') && ((*end) != ':'); end++); + + if (start != end) { + is_zip = false; + filenamelen = end - start; + + if (filenamelen > 3) { + if (strncasecmp(end - 3, "zip", 3) == 0 || + strncasecmp(end - 3, "jar", 3) == 0) { + is_zip = true; } -#endif } - if (filenamelen>=(CLASSPATH_MAXFILENAME-1)) panic("path length >= MAXFILENAME in suck_init"); - if (!filename) - filename=(char*)malloc(CLASSPATH_MAXFILENAME); - strncpy(filename,start,filenamelen); - filename[filenamelen+1]='\0'; - tmp=0; - - if (isZip) { -#ifdef USE_ZLIB - unzFile uf=unzOpen(filename); + + /* save classpath entries as absolute pathnames */ + + cwd = NULL; + cwdlen = 0; + + if (*start != '/') { /* XXX fix me for win32 */ + cwd = _Jv_getcwd(); + cwdlen = strlen(cwd) + strlen("/"); + } + + /* allocate memory for filename and fill it */ + + filename = MNEW(char, filenamelen + cwdlen + strlen("/") + + strlen("0")); + + if (cwd) { + strcpy(filename, cwd); + strcat(filename, "/"); + strncat(filename, start, filenamelen); + + /* add cwd length to file length */ + filenamelen += cwdlen; + + } else { + strncpy(filename, start, filenamelen); + filename[filenamelen] = '\0'; + } + + cpi = NULL; + + if (is_zip) { +#if defined(USE_ZLIB) + unzFile uf = unzOpen(filename); + if (uf) { - tmp=(union classpath_info*)malloc(sizeof(classpath_info)); - tmp->archive.type=CLASSPATH_ARCHIVE; - tmp->archive.uf=uf; - tmp->archive.next=0; - filename=0; + cpi = NEW(classpath_info); + cpi->type = CLASSPATH_ARCHIVE; + cpi->uf = uf; + cpi->next = NULL; + cpi->path = filename; + cpi->pathlen = filenamelen; + + /* SUN compatible -verbose:class output */ + + if (opt_verboseclass) + printf("[Opened %s]\n", filename); } + #else - panic("Zip/JAR not supported"); + throw_cacao_exception_exit(string_java_lang_InternalError, + "zip/jar files not supported"); #endif } else { - tmp=(union classpath_info*)malloc(sizeof(classpath_info)); - tmp->filepath.type=CLASSPATH_PATH; - tmp->filepath.next=0; - if (filename[filenamelen-1]!='/') {/*PERHAPS THIS SHOULD BE READ FROM A GLOBAL CONFIGURATION */ - filename[filenamelen]='/'; - filename[filenamelen+1]='\0'; + cpi = NEW(classpath_info); + cpi->type = CLASSPATH_PATH; + cpi->next = NULL; + + if (filename[filenamelen - 1] != '/') {/*PERHAPS THIS SHOULD BE READ FROM A GLOBAL CONFIGURATION */ + filename[filenamelen] = '/'; + filename[filenamelen + 1] = '\0'; filenamelen++; } - - tmp->filepath.filename=filename; - tmp->filepath.pathlen=filenamelen; - filename=0; + + cpi->path = filename; + cpi->pathlen = filenamelen; } - if (tmp) { - if (insertAfter) { - insertAfter->filepath.next=tmp; - } else { - classpath_entries=tmp; + /* attach current classpath entry */ + + if (cpi) { + if (!classpath_entries) + classpath_entries = cpi; + else + lastcpi->next = cpi; + + lastcpi = cpi; } - insertAfter=tmp; + } + + /* goto next classpath entry, skip ':' delimiter */ + + if ((*end) == ':') { + start = end + 1; + + } else { + start = end; } } - if ((*end)==':') start=end+1; else start=end; - - - if (filename!=0) free(filename); } + +/* loader_load_all_classes ***************************************************** + + Loads all classes specified in the BOOTCLASSPATH. + +*******************************************************************************/ + +void loader_load_all_classes(void) +{ + classpath_info *cpi; + classinfo *c; + + for (cpi = classpath_entries; cpi != 0; cpi = cpi->next) { +#if defined(USE_ZLIB) + if (cpi->type == CLASSPATH_ARCHIVE) { + cacao_entry_s *ce; + unz_s *s; + + s = (unz_s *) cpi->uf; + ce = s->cacao_dir_list; + + while (ce) { + /* skip all entries in META-INF and .properties, .png files */ + + if (strncmp(ce->name->text, "META-INF", strlen("META-INF")) && + !strstr(ce->name->text, ".properties") && + !strstr(ce->name->text, ".png")) + c = load_class_bootstrap(ce->name); + + ce = ce->next; + } + + } else { +#endif +#if defined(USE_ZLIB) + } +#endif + } } -/************************** function suck_start ******************************** - returns true if classbuffer is already loaded or a file for the - specified class has succussfully been read in. All directories of - the searchpath are used to find the classfile (.class). - Returns false if no classfile is found and writes an error message. +/* suck_start ****************************************************************** + + Returns true if classbuffer is already loaded or a file for the + specified class has succussfully been read in. All directories of + the searchpath are used to find the classfile (.class). + Returns false if no classfile is found and writes an error message. *******************************************************************************/ -bool suck_start(utf *classname) +classbuffer *suck_start(classinfo *c) { - classpath_info *currPos; - char *utf_ptr; - char c; - char filename[CLASSPATH_MAXFILENAME+10]; /* room for '.class' */ - int filenamelen=0; + classpath_info *cpi; + char *filename; + s4 filenamelen; + char *path; FILE *classfile; - int err; + bool found; + s4 len; struct stat buffer; + classbuffer *cb; - if (classbuffer) return true; /* classbuffer is already valid */ + /* initialize return value */ - utf_ptr = classname->text; - while (utf_ptr < utf_end(classname)) { - PANICIF (filenamelen >= CLASSPATH_MAXFILENAME, "Filename too long"); - c = *utf_ptr++; - if ((c <= ' ' || c > 'z') && (c != '/')) /* invalid character */ - c = '?'; - filename[filenamelen++] = c; - } - strcpy(filename + filenamelen, ".class"); - filenamelen+=6; - for (currPos=classpath_entries;currPos!=0;currPos=currPos->filepath.next) { -#ifdef USE_ZLIB - if (currPos->filepath.type==CLASSPATH_ARCHIVE) { - if (cacao_locate(currPos->archive.uf,classname) == UNZ_OK) { + found = false; + cb = NULL; + + filenamelen = utf_strlen(c->name) + strlen(".class") + strlen("0"); + filename = MNEW(char, filenamelen); + + utf_sprint(filename, c->name); + strcat(filename, ".class"); + + /* walk through all classpath entries */ + + for (cpi = classpath_entries; cpi != NULL && cb == NULL; cpi = cpi->next) { +#if defined(USE_ZLIB) + if (cpi->type == CLASSPATH_ARCHIVE) { + +#if defined(USE_THREADS) + /* enter a monitor on zip/jar archives */ + + builtin_monitorenter((java_objectheader *) cpi); +#endif + + if (cacao_locate(cpi->uf, c->name) == UNZ_OK) { unz_file_info file_info; - /*log_text("Class found in zip file");*/ - if (unzGetCurrentFileInfo(currPos->archive.uf, &file_info, filename, - sizeof(filename), NULL, 0, NULL, 0) == UNZ_OK) { - if (unzOpenCurrentFile(currPos->archive.uf) == UNZ_OK) { - classbuffer_size = file_info.uncompressed_size; - classbuffer = MNEW(u1, classbuffer_size); - classbuf_pos = classbuffer - 1; - /*printf("classfile size: %d\n",file_info.uncompressed_size);*/ - if (unzReadCurrentFile(currPos->archive.uf, classbuffer, classbuffer_size) == classbuffer_size) { - unzCloseCurrentFile(currPos->archive.uf); - return true; - } else { - MFREE(classbuffer, u1, classbuffer_size); + + if (unzGetCurrentFileInfo(cpi->uf, &file_info, filename, + sizeof(filename), NULL, 0, NULL, 0) == UNZ_OK) { + if (unzOpenCurrentFile(cpi->uf) == UNZ_OK) { + cb = NEW(classbuffer); + cb->class = c; + cb->size = file_info.uncompressed_size; + cb->data = MNEW(u1, cb->size); + cb->pos = cb->data - 1; + cb->path = cpi->path; + + len = unzReadCurrentFile(cpi->uf, cb->data, cb->size); + + if (len != cb->size) { + suck_stop(cb); log_text("Error while unzipping"); + + } else { + found = true; } - } else log_text("Error while opening file in archive"); - } else log_text("Error while retrieving fileinfo"); - } - unzCloseCurrentFile(currPos->archive.uf); - } else { -#endif - if ((currPos->filepath.pathlen+filenamelen)>=CLASSPATH_MAXFILENAME) continue; - strcpy(currPos->filepath.filename+currPos->filepath.pathlen,filename); - classfile = fopen(currPos->filepath.filename, "r"); - if (classfile) { /* file exists */ + } else { + log_text("Error while opening file in archive"); + } - /* determine size of classfile */ + } else { + log_text("Error while retrieving fileinfo"); + } + } + unzCloseCurrentFile(cpi->uf); - /* dolog("File: %s",filename); */ +#if defined(USE_THREADS) + /* leave the monitor */ - err = stat(currPos->filepath.filename, &buffer); + builtin_monitorexit((java_objectheader *) cpi); +#endif - if (!err) { /* read classfile data */ - classbuffer_size = buffer.st_size; - classbuffer = MNEW(u1, classbuffer_size); - classbuf_pos = classbuffer - 1; - fread(classbuffer, 1, classbuffer_size, classfile); - fclose(classfile); - return true; + } else { +#endif /* defined(USE_ZLIB) */ + + path = MNEW(char, cpi->pathlen + filenamelen); + strcpy(path, cpi->path); + strcat(path, filename); + + classfile = fopen(path, "r"); + + if (classfile) { /* file exists */ + if (!stat(path, &buffer)) { /* read classfile data */ + cb = NEW(classbuffer); + cb->class = c; + cb->size = buffer.st_size; + cb->data = MNEW(u1, cb->size); + cb->pos = cb->data - 1; + cb->path = cpi->path; + + /* read class data */ + len = fread(cb->data, 1, cb->size, classfile); + + if (len != buffer.st_size) { + suck_stop(cb); +/* if (ferror(classfile)) { */ +/* } */ + + } else { + found = true; + } } } -#ifdef USE_ZLIB + + MFREE(path, char, cpi->pathlen + filenamelen); +#if defined(USE_ZLIB) } #endif } - if (verbose) { - dolog("Warning: Can not open class file '%s'", filename); - } + if (opt_verbose) + if (!found) { + dolog("Warning: Can not open class file '%s'", filename); + + if (strcmp(filename, "org/mortbay/util/MultiException.class") == 0) { + static int i = 0; + i++; + if (i == 3) + assert(0); + } + } - return false; + MFREE(filename, char, filenamelen); + return cb; } + /************************** function suck_stop ********************************* frees memory for buffer with classfile data. @@ -517,24 +733,12 @@ bool suck_start(utf *classname) *******************************************************************************/ -void suck_stop() +void suck_stop(classbuffer *cb) { - /* determine amount of classdata not retrieved by suck-operations */ - - int classdata_left = ((classbuffer + classbuffer_size) - classbuf_pos - 1); - - if (classdata_left > 0) { - /* surplus */ - dolog("There are %d extra bytes at end of classfile", - classdata_left); - /* The JVM spec disallows extra bytes. */ - panic("Extra bytes at end of classfile"); - } - /* free memory */ - MFREE(classbuffer, u1, classbuffer_size); - classbuffer = NULL; + MFREE(cb->data, u1, cb->size); + FREE(cb, classbuffer); } @@ -562,32 +766,7 @@ void fprintflags (FILE *fp, u2 f) void printflags(u2 f) { - if ( f & ACC_PUBLIC ) printf (" PUBLIC"); - if ( f & ACC_PRIVATE ) printf (" PRIVATE"); - if ( f & ACC_PROTECTED ) printf (" PROTECTED"); - if ( f & ACC_STATIC ) printf (" STATIC"); - if ( f & ACC_FINAL ) printf (" FINAL"); - if ( f & ACC_SYNCHRONIZED ) printf (" SYNCHRONIZED"); - if ( f & ACC_VOLATILE ) printf (" VOLATILE"); - if ( f & ACC_TRANSIENT ) printf (" TRANSIENT"); - if ( f & ACC_NATIVE ) printf (" NATIVE"); - if ( f & ACC_INTERFACE ) printf (" INTERFACE"); - if ( f & ACC_ABSTRACT ) printf (" ABSTRACT"); -} - - -/************************* Function: skipattribute ***************************** - - skips a (1) 'attribute' structure in the class file - -*******************************************************************************/ - -static void skipattribute() -{ - u4 len; - suck_u2 (); - len = suck_u4(); - skip_nbytes(len); + fprintflags(stdout,f); } @@ -598,11 +777,21 @@ static void skipattribute() *******************************************************************************/ -static void skipattributebody() +static bool skipattributebody(classbuffer *cb) { u4 len; - len = suck_u4(); - skip_nbytes(len); + + if (!check_classbuffer_size(cb, 4)) + return false; + + len = suck_u4(cb); + + if (!check_classbuffer_size(cb, len)) + return false; + + skip_nbytes(cb, len); + + return true; } @@ -612,739 +801,37 @@ static void skipattributebody() *******************************************************************************/ -static void skipattributes(u4 num) +static bool skipattributes(classbuffer *cb, u4 num) { u4 i; - for (i = 0; i < num; i++) - skipattribute(); -} - - -/******************** function: innerclass_getconstant ************************ + u4 len; - like class_getconstant, but if cptags is ZERO null is returned - -*******************************************************************************/ + for (i = 0; i < num; i++) { + if (!check_classbuffer_size(cb, 2 + 4)) + return false; -voidptr innerclass_getconstant(classinfo *c, u4 pos, u4 ctype) -{ - /* invalid position in constantpool */ - if (pos >= c->cpcount) - panic("Attempt to access constant outside range"); + suck_u2(cb); + len = suck_u4(cb); - /* constantpool entry of type 0 */ - if (!c->cptags[pos]) - return NULL; + if (!check_classbuffer_size(cb, len)) + return false; - /* check type of constantpool entry */ - if (c->cptags[pos] != ctype) { - error("Type mismatch on constant: %d requested, %d here (innerclass_getconstant)", - (int) ctype, (int) c->cptags[pos] ); + skip_nbytes(cb, len); } - - return c->cpinfos[pos]; + + return true; } -/************************ function: attribute_load **************************** +/* load_constantpool *********************************************************** + + Loads the constantpool of a class, the entries are transformed into + a simpler format by resolving references (a detailed overview of + the compact structures can be found in global.h). - read attributes from classfile - *******************************************************************************/ -static void attribute_load(u4 num, classinfo *c) -{ - u4 i, j; - - for (i = 0; i < num; i++) { - /* retrieve attribute name */ - utf *aname = class_getconstant(c, suck_u2(), CONSTANT_Utf8); - - if (aname == utf_innerclasses) { - /* innerclasses attribute */ - - if (c->innerclass != NULL) - panic("Class has more than one InnerClasses attribute"); - - /* skip attribute length */ - suck_u4(); - /* number of records */ - c->innerclasscount = suck_u2(); - /* allocate memory for innerclass structure */ - c->innerclass = MNEW(innerclassinfo, c->innerclasscount); - - for (j = 0; j < c->innerclasscount; j++) { - /* The innerclass structure contains a class with an encoded name, - its defining scope, its simple name and a bitmask of the access flags. - If an inner class is not a member, its outer_class is NULL, - if a class is anonymous, its name is NULL. */ - - innerclassinfo *info = c->innerclass + j; - - info->inner_class = innerclass_getconstant(c, suck_u2(), CONSTANT_Class); /* CONSTANT_Class_info index */ - info->outer_class = innerclass_getconstant(c, suck_u2(), CONSTANT_Class); /* CONSTANT_Class_info index */ - info->name = innerclass_getconstant(c, suck_u2(), CONSTANT_Utf8); /* CONSTANT_Utf8_info index */ - info->flags = suck_u2(); /* access_flags bitmask */ - } - - } else { - /* unknown attribute */ - skipattributebody(); - } - } -} - - -/******************* function: checkfielddescriptor **************************** - - checks whether a field-descriptor is valid and aborts otherwise - all referenced classes are inserted into the list of unloaded classes - -*******************************************************************************/ - -static void checkfielddescriptor (char *utf_ptr, char *end_pos) -{ - class_from_descriptor(utf_ptr,end_pos,NULL, - CLASSLOAD_NEW - | CLASSLOAD_NULLPRIMITIVE - | CLASSLOAD_NOVOID - | CLASSLOAD_CHECKEND); - - /* XXX use the following if -noverify */ -#if 0 - char *tstart; /* pointer to start of classname */ - char ch; - char *start = utf_ptr; - - switch (*utf_ptr++) { - case 'B': - case 'C': - case 'I': - case 'S': - case 'Z': - case 'J': - case 'F': - case 'D': - /* primitive type */ - break; - - case '[': - case 'L': - if (!class_from_descriptor(start,end_pos,&utf_ptr,CLASSLOAD_NEW)) - panic ("Ill formed descriptor"); - break; - - default: - panic ("Ill formed descriptor"); - } - - /* exceeding characters */ - if (utf_ptr!=end_pos) panic ("descriptor has exceeding chars"); -#endif -} - - -/******************* function checkmethoddescriptor **************************** - - checks whether a method-descriptor is valid and aborts otherwise. - All referenced classes are inserted into the list of unloaded classes. - - The number of arguments is returned. A long or double argument is counted - as two arguments. - -*******************************************************************************/ - -static int checkmethoddescriptor (utf *d) -{ - char *utf_ptr = d->text; /* current position in utf text */ - char *end_pos = utf_end(d); /* points behind utf string */ - int argcount = 0; /* number of arguments */ - - /* method descriptor must start with parenthesis */ - if (utf_ptr == end_pos || *utf_ptr++ != '(') panic ("Missing '(' in method descriptor"); - - /* check arguments */ - while (utf_ptr != end_pos && *utf_ptr != ')') { - /* We cannot count the this argument here because - * we don't know if the method is static. */ - if (*utf_ptr == 'J' || *utf_ptr == 'D') - argcount+=2; - else - argcount++; - class_from_descriptor(utf_ptr,end_pos,&utf_ptr, - CLASSLOAD_NEW - | CLASSLOAD_NULLPRIMITIVE - | CLASSLOAD_NOVOID); - } - - if (utf_ptr == end_pos) panic("Missing ')' in method descriptor"); - utf_ptr++; /* skip ')' */ - - class_from_descriptor(utf_ptr,end_pos,NULL, - CLASSLOAD_NEW - | CLASSLOAD_NULLPRIMITIVE - | CLASSLOAD_CHECKEND); - - if (argcount > 255) - panic("Invalid method descriptor: too many arguments"); - - return argcount; - - /* XXX use the following if -noverify */ -#if 0 - /* check arguments */ - while ((c = *utf_ptr++) != ')') { - start = utf_ptr-1; - - switch (c) { - case 'B': - case 'C': - case 'I': - case 'S': - case 'Z': - case 'J': - case 'F': - case 'D': - /* primitive type */ - break; - - case '[': - case 'L': - if (!class_from_descriptor(start,end_pos,&utf_ptr,CLASSLOAD_NEW)) - panic ("Ill formed method descriptor"); - break; - - default: - panic ("Ill formed methodtype-descriptor"); - } - } - - /* check returntype */ - if (*utf_ptr=='V') { - /* returntype void */ - if ((utf_ptr+1) != end_pos) panic ("Method-descriptor has exceeding chars"); - } - else - /* treat as field-descriptor */ - checkfielddescriptor (utf_ptr,end_pos); -#endif -} - - -/***************** Function: print_arraydescriptor **************************** - - Debugging helper for displaying an arraydescriptor - -*******************************************************************************/ - -void print_arraydescriptor(FILE *file, arraydescriptor *desc) -{ - if (!desc) { - fprintf(file, ""); - return; - } - - fprintf(file, "{"); - if (desc->componentvftbl) { - if (desc->componentvftbl->class) - utf_fprint(file, desc->componentvftbl->class->name); - else - fprintf(file, ""); - } - else - fprintf(file, "0"); - - fprintf(file, ","); - if (desc->elementvftbl) { - if (desc->elementvftbl->class) - utf_fprint(file, desc->elementvftbl->class->name); - else - fprintf(file, ""); - } - else - fprintf(file, "0"); - fprintf(file, ",%d,%d,%d,%d}", desc->arraytype, desc->dimension, - desc->dataoffset, desc->componentsize); -} - - -/******************************************************************************/ -/************************** Functions for fields ****************************/ -/******************************************************************************/ - - -/************************ Function: field_load ********************************* - - Load everything about a class field from the class file and fill a - 'fieldinfo' structure. For static fields, space in the data segment is - allocated. - -*******************************************************************************/ - -#define field_load_NOVALUE 0xffffffff /* must be bigger than any u2 value! */ - -static void field_load(fieldinfo *f, classinfo *c) -{ - u4 attrnum,i; - u4 jtype; - u4 pindex = field_load_NOVALUE; /* constantvalue_index */ - - f->flags = suck_u2(); /* ACC flags */ - f->name = class_getconstant(c, suck_u2(), CONSTANT_Utf8); /* name of field */ - f->descriptor = class_getconstant(c, suck_u2(), CONSTANT_Utf8); /* JavaVM descriptor */ - - if (opt_verify) { - /* check name */ - if (!is_valid_name_utf(f->name) || f->name->text[0] == '<') - panic("Field with invalid name"); - - /* check flag consistency */ - i = (f->flags & (ACC_PUBLIC | ACC_PRIVATE | ACC_PROTECTED)); - if (i != 0 && i != ACC_PUBLIC && i != ACC_PRIVATE && i != ACC_PROTECTED) - panic("Field has invalid access flags"); - if ((f->flags & (ACC_FINAL | ACC_VOLATILE)) == (ACC_FINAL | ACC_VOLATILE)) - panic("Field is declared final and volatile"); - if ((c->flags & ACC_INTERFACE) != 0) { - if ((f->flags & (ACC_STATIC | ACC_PUBLIC | ACC_FINAL)) - != (ACC_STATIC | ACC_PUBLIC | ACC_FINAL)) - panic("Interface field is not declared static final public"); - if ((f->flags & ACC_TRANSIENT) != 0) - panic("Interface field declared transient"); - } - - /* check descriptor */ - checkfielddescriptor(f->descriptor->text,utf_end(f->descriptor)); - } - - f->type = jtype = desc_to_type(f->descriptor); /* data type */ - f->offset = 0; /* offset from start of object */ - f->class = c; - f->xta = NULL; - - switch (f->type) { - case TYPE_INT: f->value.i = 0; break; - case TYPE_FLOAT: f->value.f = 0.0; break; - case TYPE_DOUBLE: f->value.d = 0.0; break; - case TYPE_ADDRESS: f->value.a = NULL; break; - case TYPE_LONG: -#if U8_AVAILABLE - f->value.l = 0; break; -#else - f->value.l.low = 0; f->value.l.high = 0; break; -#endif - } - - /* read attributes */ - attrnum = suck_u2(); - for (i = 0; i < attrnum; i++) { - utf *aname; - - aname = class_getconstant(c, suck_u2(), CONSTANT_Utf8); - - if (aname != utf_constantvalue) { - /* unknown attribute */ - skipattributebody(); - - } else { - /* constant value attribute */ - - if (pindex != field_load_NOVALUE) - panic("Field has more than one ConstantValue attribute"); - - /* check attribute length */ - if (suck_u4() != 2) - panic("ConstantValue attribute has invalid length"); - - /* index of value in constantpool */ - pindex = suck_u2(); - - /* initialize field with value from constantpool */ - switch (jtype) { - case TYPE_INT: { - constant_integer *ci = - class_getconstant(c, pindex, CONSTANT_Integer); - f->value.i = ci->value; - } - break; - - case TYPE_LONG: { - constant_long *cl = - class_getconstant(c, pindex, CONSTANT_Long); - f->value.l = cl->value; - } - break; - - case TYPE_FLOAT: { - constant_float *cf = - class_getconstant(c, pindex, CONSTANT_Float); - f->value.f = cf->value; - } - break; - - case TYPE_DOUBLE: { - constant_double *cd = - class_getconstant(c, pindex, CONSTANT_Double); - f->value.d = cd->value; - } - break; - - case TYPE_ADDRESS: { - utf *u = class_getconstant(c, pindex, CONSTANT_String); - /* create javastring from compressed utf8-string */ - f->value.a = literalstring_new(u); - } - break; - - default: - log_text ("Invalid Constant - Type"); - } - } - } -} - - -/********************** function: field_free **********************************/ - -static void field_free (fieldinfo *f) -{ - /* empty */ -} - - -/**************** Function: field_display (debugging only) ********************/ - -void field_display(fieldinfo *f) -{ - printf(" "); - printflags(f->flags); - printf(" "); - utf_display(f->name); - printf(" "); - utf_display(f->descriptor); - printf(" offset: %ld\n", (long int) (f->offset)); -} - - -/******************************************************************************/ -/************************* Functions for methods ******************************/ -/******************************************************************************/ - - -/*********************** Function: method_load ********************************* - - Loads a method from the class file and fills an existing 'methodinfo' - structure. For native methods, the function pointer field is set to the - real function pointer, for JavaVM methods a pointer to the compiler is used - preliminarily. - -*******************************************************************************/ - -static void method_load(methodinfo *m, classinfo *c) -{ - u4 attrnum, i, e; - int argcount; - -#ifdef STATISTICS - count_all_methods++; -#endif - m->thrownexceptionscount=0; - m->linenumbercount=0; - m->linenumbers=0; - m->class = c; - - m->flags = suck_u2(); - m->name = class_getconstant(c, suck_u2(), CONSTANT_Utf8); - - if (opt_verify) { - if (!is_valid_name_utf(m->name)) - panic("Method with invalid name"); - if (m->name->text[0] == '<' - && m->name != utf_init && m->name != utf_clinit) - panic("Method with invalid special name"); - } - - m->descriptor = class_getconstant(c, suck_u2(), CONSTANT_Utf8); - argcount = checkmethoddescriptor(m->descriptor); - if ((m->flags & ACC_STATIC) == 0) - argcount++; /* count the 'this' argument */ - - if (opt_verify) { - if (argcount > 255) - panic("Method has more than 255 arguments"); - - /* check flag consistency */ - if (m->name != utf_clinit) { - i = (m->flags & (ACC_PUBLIC | ACC_PRIVATE | ACC_PROTECTED)); - if (i != 0 && i != ACC_PUBLIC && i != ACC_PRIVATE && i != ACC_PROTECTED) - panic("Method has invalid access flags"); - if ((m->flags & ACC_ABSTRACT) != 0) { - if ((m->flags & (ACC_FINAL | ACC_NATIVE | ACC_PRIVATE | ACC_STATIC - | ACC_STRICT | ACC_SYNCHRONIZED)) != 0) - panic("Abstract method has invalid flags set"); - } - if ((c->flags & ACC_INTERFACE) != 0) { - if ((m->flags & (ACC_ABSTRACT | ACC_PUBLIC)) - != (ACC_ABSTRACT | ACC_PUBLIC)) - panic("Interface method is not declared abstract and public"); - } - if (m->name == utf_init) { - if ((m->flags & (ACC_STATIC | ACC_FINAL | ACC_SYNCHRONIZED - | ACC_NATIVE | ACC_ABSTRACT)) != 0) - panic("Instance initialization method has invalid flags set"); - } - } - } - - m->jcode = NULL; - m->exceptiontable = NULL; - m->entrypoint = NULL; - m->mcode = NULL; - m->stubroutine = NULL; - m->methodUsed = NOTUSED; - m->monoPoly = MONO; - m->subRedefs = 0; - m->subRedefsUsed = 0; - - m->xta = NULL; - - if (!(m->flags & ACC_NATIVE)) { - m->stubroutine = createcompilerstub(m); - - } else { - functionptr f = native_findfunction(c->name, m->name, m->descriptor, - (m->flags & ACC_STATIC) != 0); - if (f) { - m->stubroutine = createnativestub(f, m); - } - } - - - attrnum = suck_u2(); - for (i = 0; i < attrnum; i++) { - utf *aname; - - aname = class_getconstant(c, suck_u2(), CONSTANT_Utf8); - - if (aname != utf_code) { - if (aname == utf_exceptions) { - u2 exceptionCount; - u2 exceptionID; - suck_u4(); /*length*/ - exceptionCount=suck_u2(); - m->thrownexceptionscount=exceptionCount; - m->thrownexceptions=MNEW(classinfo*,exceptionCount); - for (exceptionID=0;exceptionIDthrownexceptions)[exceptionID]=class_getconstant(c,suck_u2(),CONSTANT_Class); - } - } - else - skipattributebody(); - - } else { - u4 codelen; - if ((m->flags & (ACC_ABSTRACT | ACC_NATIVE)) != 0) - panic("Code attribute for native or abstract method"); - - if (m->jcode) - panic("Method has more than one Code attribute"); - - suck_u4(); - m->maxstack = suck_u2(); - m->maxlocals = suck_u2(); - if (m->maxlocals < argcount) - panic("max_locals is smaller than the number of arguments"); - - codelen = suck_u4(); - if (codelen == 0) - panic("bytecode has zero length"); - if (codelen > 65536) - panic("bytecode too long"); - m->jcodelength = codelen; - m->jcode = MNEW(u1, m->jcodelength); - suck_nbytes(m->jcode, m->jcodelength); - m->exceptiontablelength = suck_u2(); - m->exceptiontable = - MNEW(exceptiontable, m->exceptiontablelength); - -#ifdef STATISTICS - count_vmcode_len += m->jcodelength + 18; - count_extable_len += 8 * m->exceptiontablelength; -#endif - - for (e = 0; e < m->exceptiontablelength; e++) { - u4 idx; - m->exceptiontable[e].startpc = suck_u2(); - m->exceptiontable[e].endpc = suck_u2(); - m->exceptiontable[e].handlerpc = suck_u2(); - - idx = suck_u2(); - if (!idx) { - m->exceptiontable[e].catchtype = NULL; - - } else { - m->exceptiontable[e].catchtype = - class_getconstant(c, idx, CONSTANT_Class); - } - } - { - u2 codeattrnum; - for (codeattrnum=suck_u2();codeattrnum>0;codeattrnum--) { - utf * caname = class_getconstant(c, suck_u2(), CONSTANT_Utf8); - if (caname==utf_linenumbertable) { - u2 lncid; - /*log_text("LineNumberTable found");*/ - suck_u4(); - m->linenumbercount=suck_u2(); - /*printf("length:%d\n",m->linenumbercount);*/ - m->linenumbers=MNEW(lineinfo,m->linenumbercount); - for (lncid=0;lncidlinenumbercount;lncid++) { - m->linenumbers[lncid].start_pc=suck_u2(); - m->linenumbers[lncid].line_number=suck_u2(); - } - codeattrnum--; - skipattributes(codeattrnum); - break; - } else skipattributebody(); - - } - } - } - } - - if (!m->jcode && (m->flags & (ACC_ABSTRACT | ACC_NATIVE)) == 0) - panic("Method missing Code attribute"); -} - - -/********************* Function: method_free *********************************** - - frees all memory that was allocated for this method - -*******************************************************************************/ - -static void method_free(methodinfo *m) -{ - if (m->jcode) - MFREE(m->jcode, u1, m->jcodelength); - - if (m->exceptiontable) - MFREE(m->exceptiontable, exceptiontable, m->exceptiontablelength); - - if (m->mcode) - CFREE(m->mcode, m->mcodelength); - - if (m->stubroutine) { - if (m->flags & ACC_NATIVE) { - removenativestub(m->stubroutine); - - } else { - removecompilerstub(m->stubroutine); - } - } -} - - -/************** Function: method_display (debugging only) **************/ - -void method_display(methodinfo *m) -{ - printf(" "); - printflags(m->flags); - printf(" "); - utf_display(m->name); - printf(" "); - utf_display(m->descriptor); - printf("\n"); -} - -/************** Function: method_display_flags_last (debugging only) **************/ - -void method_display_flags_last(methodinfo *m) -{ - printf(" "); - utf_display(m->name); - printf(" "); - utf_display(m->descriptor); - printf(" "); - printflags(m->flags); - printf("\n"); -} - - -/******************** Function: method_canoverwrite **************************** - - Check if m and old are identical with respect to type and name. This means - that old can be overwritten with m. - -*******************************************************************************/ - -static bool method_canoverwrite (methodinfo *m, methodinfo *old) -{ - if (m->name != old->name) return false; - if (m->descriptor != old->descriptor) return false; - if (m->flags & ACC_STATIC) return false; - return true; -} - - - - -/******************************************************************************/ -/************************ Functions for class *********************************/ -/******************************************************************************/ - - -/******************** function:: class_getconstant ****************************** - - retrieves the value at position 'pos' of the constantpool of a class - if the type of the value is other than 'ctype' the system is stopped - -*******************************************************************************/ - -voidptr class_getconstant(classinfo *c, u4 pos, u4 ctype) -{ - /* invalid position in constantpool */ - /* (pos == 0 is caught by type comparison) */ - if (pos >= c->cpcount) - panic("Attempt to access constant outside range"); - - /* check type of constantpool entry */ - - if (c->cptags[pos] != ctype) { - class_showconstantpool(c); - error("Type mismatch on constant: %d requested, %d here (class_getconstant)", - (int) ctype, (int) c->cptags[pos]); - } - - return c->cpinfos[pos]; -} - - -/********************* Function: class_constanttype **************************** - - Determines the type of a class entry in the ConstantPool - -*******************************************************************************/ - -u4 class_constanttype(classinfo *c, u4 pos) -{ - if (pos >= c->cpcount) - panic("Attempt to access constant outside range"); - - return c->cptags[pos]; -} - - -/******************** function: class_loadcpool ******************************** - - loads the constantpool of a class, - the entries are transformed into a simpler format - by resolving references - (a detailed overview of the compact structures can be found in global.h) - -*******************************************************************************/ - -static void class_loadcpool(classinfo *c) +static bool load_constantpool(classbuffer *cb, descriptor_pool *descpool) { /* The following structures are used to save information which cannot be @@ -1352,17 +839,17 @@ static void class_loadcpool(classinfo *c) been traversed the references can be resolved. (only in specific order) */ - /* CONSTANT_Class_info entries */ - typedef struct forward_class { - struct forward_class *next; - u2 thisindex; - u2 name_index; - } forward_class; - - /* CONSTANT_String */ - typedef struct forward_string { - struct forward_string *next; - u2 thisindex; + /* CONSTANT_Class entries */ + typedef struct forward_class { + struct forward_class *next; + u2 thisindex; + u2 name_index; + } forward_class; + + /* CONSTANT_String */ + typedef struct forward_string { + struct forward_string *next; + u2 thisindex; u2 string_index; } forward_string; @@ -1375,7 +862,7 @@ static void class_loadcpool(classinfo *c) } forward_nameandtype; /* CONSTANT_Fieldref, CONSTANT_Methodref or CONSTANT_InterfaceMethodref */ - typedef struct forward_fieldmethint { + typedef struct forward_fieldmethint { struct forward_fieldmethint *next; u2 thisindex; u1 tag; @@ -1384,2586 +871,2132 @@ static void class_loadcpool(classinfo *c) } forward_fieldmethint; + classinfo *c; u4 idx; - long int dumpsize = dump_size (); forward_class *forward_classes = NULL; forward_string *forward_strings = NULL; forward_nameandtype *forward_nameandtypes = NULL; forward_fieldmethint *forward_fieldmethints = NULL; + forward_class *nfc; + forward_string *nfs; + forward_nameandtype *nfn; + forward_fieldmethint *nff; + + u4 cpcount; + u1 *cptags; + voidptr *cpinfos; + + c = cb->class; + /* number of entries in the constant_pool table plus one */ - u4 cpcount = c -> cpcount = suck_u2(); + if (!check_classbuffer_size(cb, 2)) + return false; + + cpcount = c->cpcount = suck_u2(cb); + /* allocate memory */ - u1 *cptags = c -> cptags = MNEW (u1, cpcount); - voidptr *cpinfos = c -> cpinfos = MNEW (voidptr, cpcount); + cptags = c->cptags = MNEW(u1, cpcount); + cpinfos = c->cpinfos = MNEW(voidptr, cpcount); - if (!cpcount) - panic("Invalid constant_pool_count (0)"); + if (cpcount < 1) { + *exceptionptr = new_classformaterror(c, "Illegal constant pool size"); + return false; + } -#ifdef STATISTICS - count_const_pool_len += (sizeof(voidptr) + 1) * cpcount; +#if defined(STATISTICS) + if (opt_stat) + count_const_pool_len += (sizeof(voidptr) + 1) * cpcount; #endif /* initialize constantpool */ - for (idx=0; idx next = forward_classes; - forward_classes = nfc; + switch (t) { + case CONSTANT_Class: + nfc = DNEW(forward_class); - nfc -> thisindex = idx; - /* reference to CONSTANT_NameAndType */ - nfc -> name_index = suck_u2 (); + nfc->next = forward_classes; + forward_classes = nfc; - idx++; - break; - } - - case CONSTANT_Fieldref: - case CONSTANT_Methodref: - case CONSTANT_InterfaceMethodref: { - forward_fieldmethint *nff = DNEW (forward_fieldmethint); - - nff -> next = forward_fieldmethints; - forward_fieldmethints = nff; - - nff -> thisindex = idx; - /* constant type */ - nff -> tag = t; - /* class or interface type that contains the declaration of the field or method */ - nff -> class_index = suck_u2 (); - /* name and descriptor of the field or method */ - nff -> nameandtype_index = suck_u2 (); - - idx ++; - break; - } - - case CONSTANT_String: { - forward_string *nfs = DNEW (forward_string); - - nfs -> next = forward_strings; - forward_strings = nfs; - - nfs -> thisindex = idx; - /* reference to CONSTANT_Utf8_info with string characters */ - nfs -> string_index = suck_u2 (); - - idx ++; - break; - } + nfc->thisindex = idx; + /* reference to CONSTANT_NameAndType */ + if (!check_classbuffer_size(cb, 2)) + return false; - case CONSTANT_NameAndType: { - forward_nameandtype *nfn = DNEW (forward_nameandtype); - - nfn -> next = forward_nameandtypes; - forward_nameandtypes = nfn; + nfc->name_index = suck_u2(cb); + + idx++; + break; + + case CONSTANT_String: + nfs = DNEW(forward_string); - nfn -> thisindex = idx; - /* reference to CONSTANT_Utf8_info containing simple name */ - nfn -> name_index = suck_u2 (); - /* reference to CONSTANT_Utf8_info containing field or method descriptor */ - nfn -> sig_index = suck_u2 (); + nfs->next = forward_strings; + forward_strings = nfs; - idx ++; - break; - } + nfs->thisindex = idx; - case CONSTANT_Integer: { - constant_integer *ci = NEW (constant_integer); + /* reference to CONSTANT_Utf8_info with string characters */ + if (!check_classbuffer_size(cb, 2)) + return false; -#ifdef STATISTICS - count_const_pool_len += sizeof(constant_integer); -#endif + nfs->string_index = suck_u2(cb); + + idx++; + break; - ci -> value = suck_s4 (); - cptags [idx] = CONSTANT_Integer; - cpinfos [idx] = ci; - idx ++; + case CONSTANT_NameAndType: + nfn = DNEW(forward_nameandtype); - break; - } + nfn->next = forward_nameandtypes; + forward_nameandtypes = nfn; - case CONSTANT_Float: { - constant_float *cf = NEW (constant_float); + nfn->thisindex = idx; -#ifdef STATISTICS - count_const_pool_len += sizeof(constant_float); -#endif + if (!check_classbuffer_size(cb, 2 + 2)) + return false; - cf -> value = suck_float (); - cptags [idx] = CONSTANT_Float; - cpinfos[idx] = cf; - idx ++; - break; - } - - case CONSTANT_Long: { - constant_long *cl = NEW(constant_long); - -#ifdef STATISTICS - count_const_pool_len += sizeof(constant_long); -#endif + /* reference to CONSTANT_Utf8_info containing simple name */ + nfn->name_index = suck_u2(cb); - cl -> value = suck_s8 (); - cptags [idx] = CONSTANT_Long; - cpinfos [idx] = cl; - idx += 2; - if (idx > cpcount) - panic("Long constant exceeds constant pool"); - break; - } - - case CONSTANT_Double: { - constant_double *cd = NEW(constant_double); + /* reference to CONSTANT_Utf8_info containing field or method + descriptor */ + nfn->sig_index = suck_u2(cb); -#ifdef STATISTICS - count_const_pool_len += sizeof(constant_double); -#endif + idx++; + break; - cd -> value = suck_double (); - cptags [idx] = CONSTANT_Double; - cpinfos [idx] = cd; - idx += 2; - if (idx > cpcount) - panic("Double constant exceeds constant pool"); - break; - } - - case CONSTANT_Utf8: { - - /* number of bytes in the bytes array (not string-length) */ - u4 length = suck_u2(); - cptags [idx] = CONSTANT_Utf8; - /* validate the string */ - ASSERT_LEFT(length); - if (opt_verify && - !is_valid_utf(classbuf_pos+1, classbuf_pos+1+length)) - { - dolog("Invalid UTF-8 string (constant pool index %d)",idx); - panic("Invalid UTF-8 string"); - } - /* insert utf-string into the utf-symboltable */ - cpinfos [idx] = utf_new(classbuf_pos+1, length); - /* skip bytes of the string */ - skip_nbytes(length); - idx++; - break; - } - - default: - error ("Unkown constant type: %d",(int) t); - - } /* end switch */ + case CONSTANT_Fieldref: + case CONSTANT_Methodref: + case CONSTANT_InterfaceMethodref: + nff = DNEW(forward_fieldmethint); - } /* end while */ - - - - /* resolve entries in temporary structures */ - - while (forward_classes) { - utf *name = - class_getconstant (c, forward_classes -> name_index, CONSTANT_Utf8); + nff->next = forward_fieldmethints; + forward_fieldmethints = nff; - if (opt_verify && !is_valid_name_utf(name)) - panic("Class reference with invalid name"); + nff->thisindex = idx; + /* constant type */ + nff->tag = t; - cptags [forward_classes -> thisindex] = CONSTANT_Class; - /* retrieve class from class-table */ - cpinfos [forward_classes -> thisindex] = class_new (name); + if (!check_classbuffer_size(cb, 2 + 2)) + return false; - forward_classes = forward_classes -> next; - - } + /* class or interface type that contains the declaration of the + field or method */ + nff->class_index = suck_u2(cb); - while (forward_strings) { - utf *text = - class_getconstant (c, forward_strings -> string_index, CONSTANT_Utf8); -/* - log_text("forward_string:"); - printf( "classpoolid: %d\n",forward_strings -> thisindex); - utf_display(text); - log_text("\n------------------"); */ - /* resolve utf-string */ - cptags [forward_strings -> thisindex] = CONSTANT_String; - cpinfos [forward_strings -> thisindex] = text; - - forward_strings = forward_strings -> next; - } + /* name and descriptor of the field or method */ + nff->nameandtype_index = suck_u2(cb); - while (forward_nameandtypes) { - constant_nameandtype *cn = NEW (constant_nameandtype); + idx++; + break; + + case CONSTANT_Integer: { + constant_integer *ci = NEW(constant_integer); -#ifdef STATISTICS - count_const_pool_len += sizeof(constant_nameandtype); +#if defined(STATISTICS) + if (opt_stat) + count_const_pool_len += sizeof(constant_integer); #endif - /* resolve simple name and descriptor */ - cn -> name = class_getconstant - (c, forward_nameandtypes -> name_index, CONSTANT_Utf8); - cn -> descriptor = class_getconstant - (c, forward_nameandtypes -> sig_index, CONSTANT_Utf8); + if (!check_classbuffer_size(cb, 4)) + return false; - if (opt_verify) { - /* check name */ - if (!is_valid_name_utf(cn->name)) - panic("NameAndType with invalid name"); - /* disallow referencing among others */ - if (cn->name->text[0] == '<' && cn->name != utf_init) - panic("NameAndType with invalid special name"); - } + ci->value = suck_s4(cb); + cptags[idx] = CONSTANT_Integer; + cpinfos[idx] = ci; - cptags [forward_nameandtypes -> thisindex] = CONSTANT_NameAndType; - cpinfos [forward_nameandtypes -> thisindex] = cn; - - forward_nameandtypes = forward_nameandtypes -> next; + idx++; + break; } + + case CONSTANT_Float: { + constant_float *cf = NEW(constant_float); - - while (forward_fieldmethints) { - constant_nameandtype *nat; - constant_FMIref *fmi = NEW (constant_FMIref); - -#ifdef STATISTICS - count_const_pool_len += sizeof(constant_FMIref); -#endif - /* resolve simple name and descriptor */ - nat = class_getconstant - (c, forward_fieldmethints -> nameandtype_index, CONSTANT_NameAndType); - -#ifdef JOWENN_DEBUG - log_text("trying to resolve:"); - log_text(nat->name->text); - switch(forward_fieldmethints ->tag) { - case CONSTANT_Fieldref: - log_text("CONSTANT_Fieldref"); - break; - case CONSTANT_InterfaceMethodref: - log_text("CONSTANT_InterfaceMethodref"); - break; - case CONSTANT_Methodref: - log_text("CONSTANT_Methodref"); - break; - } +#if defined(STATISTICS) + if (opt_stat) + count_const_pool_len += sizeof(constant_float); #endif - fmi -> class = class_getconstant - (c, forward_fieldmethints -> class_index, CONSTANT_Class); - fmi -> name = nat -> name; - fmi -> descriptor = nat -> descriptor; - - cptags [forward_fieldmethints -> thisindex] = forward_fieldmethints -> tag; - cpinfos [forward_fieldmethints -> thisindex] = fmi; - - switch (forward_fieldmethints -> tag) { - case CONSTANT_Fieldref: /* check validity of descriptor */ - checkfielddescriptor (fmi->descriptor->text,utf_end(fmi->descriptor)); - break; - case CONSTANT_InterfaceMethodref: - case CONSTANT_Methodref: /* check validity of descriptor */ - checkmethoddescriptor (fmi->descriptor); - break; - } - - forward_fieldmethints = forward_fieldmethints -> next; - - } - -/* class_showconstantpool(c); */ - dump_release (dumpsize); -} - - -/********************** Function: class_load *********************************** - - Loads everything interesting about a class from the class file. The - 'classinfo' structure must have been allocated previously. - - The super class and the interfaces implemented by this class need not be - loaded. The link is set later by the function 'class_link'. - - The loaded class is removed from the list 'unloadedclasses' and added to - the list 'unlinkedclasses'. - -*******************************************************************************/ + if (!check_classbuffer_size(cb, 4)) + return false; -static int class_load(classinfo *c) -{ - u4 i; - u4 mi,ma; + cf->value = suck_float(cb); + cptags[idx] = CONSTANT_Float; + cpinfos[idx] = cf; -#ifdef STATISTICS - count_class_loads++; + idx++; + break; + } + + case CONSTANT_Long: { + constant_long *cl = NEW(constant_long); + +#if defined(STATISTICS) + if (opt_stat) + count_const_pool_len += sizeof(constant_long); #endif - /* output for debugging purposes */ - if (loadverbose) { - char logtext[MAXLOGTEXT]; - sprintf(logtext, "Loading class: "); - utf_sprint(logtext + strlen(logtext), c->name); - log_text(logtext); - } - - /* load classdata, throw exception on error */ - - if (!suck_start(c->name)) { - throw_noclassdeffounderror_message(c->name); - return false; - } - - /* check signature */ - if (suck_u4() != MAGIC) panic("Can not find class-file signature"); - /* check version */ - mi = suck_u2(); - ma = suck_u2(); - if (ma != MAJOR_VERSION && (ma != MAJOR_VERSION+1 || mi != 0)) { - error("File version %d.%d is not supported", (int) ma, (int) mi); - } - - class_loadcpool(c); - /*JOWENN*/ - c->erroneous_state = 0; - c->initializing_thread = 0; - /*JOWENN*/ - c->classUsed = NOTUSED; /* not used initially CO-RT */ - c->impldBy = NULL; - - /* ACC flags */ - c->flags = suck_u2(); - /*if (!(c->flags & ACC_PUBLIC)) { log_text("CLASS NOT PUBLIC"); } JOWENN*/ - - /* check ACC flags consistency */ - if ((c->flags & ACC_INTERFACE) != 0) { - if ((c->flags & ACC_ABSTRACT) == 0) { - /* We work around this because interfaces in JDK 1.1 are - * not declared abstract. */ - - c->flags |= ACC_ABSTRACT; - /* panic("Interface class not declared abstract"); */ + if (!check_classbuffer_size(cb, 8)) + return false; + + cl->value = suck_s8(cb); + cptags[idx] = CONSTANT_Long; + cpinfos[idx] = cl; + idx += 2; + if (idx > cpcount) { + *exceptionptr = + new_classformaterror(c, "Invalid constant pool entry"); + return false; + } + break; } - if ((c->flags & (ACC_FINAL)) != 0) - panic("Interface class has invalid flags"); - if ((c->flags & (ACC_SUPER)) != 0) - c->flags &= ~ACC_SUPER; /* kjc seems to set this on interfaces */ - } - if ((c->flags & (ACC_ABSTRACT | ACC_FINAL)) == (ACC_ABSTRACT | ACC_FINAL)) - panic("Class is declared both abstract and final"); - - /* this class */ - i = suck_u2(); - if (class_getconstant(c, i, CONSTANT_Class) != c) - panic("Invalid this_class in class file"); - - /* retrieve superclass */ - if ((i = suck_u2())) { - c->super = class_getconstant(c, i, CONSTANT_Class); + + case CONSTANT_Double: { + constant_double *cd = NEW(constant_double); + +#if defined(STATISTICS) + if (opt_stat) + count_const_pool_len += sizeof(constant_double); +#endif - /* java.lang.Object may not have a super class. */ - if (c->name == utf_java_lang_Object) - panic("java.lang.Object with super class"); - - /* Interfaces must have j.l.O as super class. */ - if ((c->flags & ACC_INTERFACE) != 0 - && c->super->name != utf_java_lang_Object) - { - panic("Interface with super class other than java.lang.Object"); + if (!check_classbuffer_size(cb, 8)) + return false; + + cd->value = suck_double(cb); + cptags[idx] = CONSTANT_Double; + cpinfos[idx] = cd; + idx += 2; + if (idx > cpcount) { + *exceptionptr = + new_classformaterror(c, "Invalid constant pool entry"); + return false; + } + break; } - } else { - c->super = NULL; - - /* This is only allowed for java.lang.Object. */ - if (c->name != utf_java_lang_Object) - panic("Class (not java.lang.Object) without super class"); - } - - /* retrieve interfaces */ - c->interfacescount = suck_u2(); - c->interfaces = MNEW(classinfo*, c->interfacescount); - for (i = 0; i < c->interfacescount; i++) { - c->interfaces [i] = - class_getconstant(c, suck_u2(), CONSTANT_Class); - } - - /* load fields */ - c->fieldscount = suck_u2(); -/* utf_display(c->name); - printf(" ,Fieldscount: %d\n",c->fieldscount);*/ - - c->fields = GCNEW(fieldinfo, c->fieldscount); - for (i = 0; i < c->fieldscount; i++) { - field_load(&(c->fields[i]), c); - } - - /* load methods */ - c->methodscount = suck_u2(); - c->methods = MNEW(methodinfo, c->methodscount); - for (i = 0; i < c->methodscount; i++) { - method_load(&(c->methods[i]), c); - } + + case CONSTANT_Utf8: { + u4 length; - /* Check if all fields and methods can be uniquely - * identified by (name,descriptor). */ - if (opt_verify) { - /* We use a hash table here to avoid making the - * average case quadratic in # of methods, fields. - */ - static int shift = 0; - u2 *hashtab; - u2 *next; /* for chaining colliding hash entries */ - size_t len; - size_t hashlen; - u2 index; - u2 old; + /* number of bytes in the bytes array (not string-length) */ + if (!check_classbuffer_size(cb, 2)) + return false; - /* Allocate hashtable */ - len = c->methodscount; - if (len < c->fieldscount) len = c->fieldscount; - hashlen = 5 * len; - hashtab = MNEW(u2,(hashlen + len)); - next = hashtab + hashlen; + length = suck_u2(cb); + cptags[idx] = CONSTANT_Utf8; - /* Determine bitshift (to get good hash values) */ - if (!shift) { - len = sizeof(utf); - while (len) { - len >>= 1; - shift++; - } - } + /* validate the string */ + if (!check_classbuffer_size(cb, length)) + return false; - /* Check fields */ - memset(hashtab,0,sizeof(u2) * (hashlen + len)); - for (i = 0; ifieldscount; ++i) { - fieldinfo *fi = c->fields + i; - /* It's ok if we lose bits here */ - index = ((((size_t)fi->name) + ((size_t)fi->descriptor)) >> shift) - % hashlen; - if ((old = hashtab[index]) != 0) { - old--; - /* dolog("HASHHIT %d --> %d",index,old); */ - next[i] = old; - do { - /* dolog("HASHCHECK %d",old); */ - if (c->fields[old].name == fi->name - && c->fields[old].descriptor == fi->descriptor) - { - dolog("Duplicate field (%d,%d):",i,old); - log_utf(fi->name); log_utf(fi->descriptor); - panic("Fields with same name and descriptor"); - } - } while ((old = next[old]) != 0); - } - /* else dolog("HASHLUCKY"); */ - hashtab[index] = i+1; - } - - /* Check methods */ - memset(hashtab,0,sizeof(u2) * (hashlen + len)); - for (i = 0; imethodscount; ++i) { - methodinfo *mi = c->methods + i; - /* It's ok if we lose bits here */ - index = ((((size_t)mi->name) + ((size_t)mi->descriptor)) >> shift) - % hashlen; - if ((old = hashtab[index]) != 0) { - old--; - /* dolog("HASHHIT %d --> %d",index,old); */ - next[i] = old; - do { - /* dolog("HASHCHECK %d",old); */ - if (c->methods[old].name == mi->name - && c->methods[old].descriptor == mi->descriptor) - { - dolog("Duplicate method (%d,%d):",i,old); - log_utf(mi->name); log_utf(mi->descriptor); - panic("Methods with same name and descriptor"); - } - } while ((old = next[old]) != 0); + if (opt_verify && + !is_valid_utf((char *) (cb->pos + 1), + (char *) (cb->pos + 1 + length))) { + *exceptionptr = new_classformaterror(c,"Invalid UTF-8 string"); + return false; } - /* else dolog("HASHLUCKY"); */ - hashtab[index] = i+1; - } - - MFREE(hashtab,u2,(hashlen + len)); - } + /* insert utf-string into the utf-symboltable */ + cpinfos[idx] = utf_new((char *) (cb->pos + 1), length); -#ifdef STATISTICS - count_class_infos += sizeof(classinfo*) * c->interfacescount; - count_class_infos += sizeof(fieldinfo) * c->fieldscount; - count_class_infos += sizeof(methodinfo) * c->methodscount; -#endif + /* skip bytes of the string (buffer size check above) */ + skip_nbytes(cb, length); + idx++; + break; + } + + default: + *exceptionptr = + new_classformaterror(c, "Illegal constant pool type"); + return false; + } /* end switch */ + } /* end while */ - /* load variable-length attribute structures */ - attribute_load(suck_u2(), c); - /* free memory */ - suck_stop(); + /* resolve entries in temporary structures */ - /* remove class from list of unloaded classes and - add to list of unlinked classes */ - list_remove(&unloadedclasses, c); - list_addlast(&unlinkedclasses, c); + while (forward_classes) { + utf *name = + class_getconstant(c, forward_classes->name_index, CONSTANT_Utf8); + if (!name) + return false; + + if (opt_verify && !is_valid_name_utf(name)) { + *exceptionptr = + new_classformaterror(c, "Class reference with invalid name"); + return false; + } - c->loaded = true; + /* add all class references to the descriptor_pool */ - return true; -} + if (!descriptor_pool_add_class(descpool, name)) + return false; + cptags[forward_classes->thisindex] = CONSTANT_Class; + if (opt_eager) { + classinfo *tc; -/************** internal Function: class_highestinterface *********************** + if (!(tc = load_class_bootstrap(name))) + return false; - Used by the function class_link to determine the amount of memory needed - for the interface table. + /* link the class later, because we cannot link the class currently + loading */ + list_addfirst(&unlinkedclasses, tc); + } -*******************************************************************************/ + /* the classref is created later */ + cpinfos[forward_classes->thisindex] = name; -static s4 class_highestinterface(classinfo *c) -{ - s4 h; - s4 i; - - if (!(c->flags & ACC_INTERFACE)) { - char logtext[MAXLOGTEXT]; - sprintf(logtext, "Interface-methods count requested for non-interface: "); - utf_sprint(logtext + strlen(logtext), c->name); - error("%s",logtext); + nfc = forward_classes; + forward_classes = forward_classes->next; } - - h = c->index; - for (i = 0; i < c->interfacescount; i++) { - s4 h2 = class_highestinterface(c->interfaces[i]); - if (h2 > h) h = h2; + + while (forward_strings) { + utf *text = + class_getconstant(c, forward_strings->string_index, CONSTANT_Utf8); + if (!text) + return false; + + /* resolve utf-string */ + cptags[forward_strings->thisindex] = CONSTANT_String; + cpinfos[forward_strings->thisindex] = text; + + nfs = forward_strings; + forward_strings = forward_strings->next; } - return h; -} + while (forward_nameandtypes) { + constant_nameandtype *cn = NEW(constant_nameandtype); +#if defined(STATISTICS) + if (opt_stat) + count_const_pool_len += sizeof(constant_nameandtype); +#endif -/* class_addinterface ********************************************************** + /* resolve simple name and descriptor */ + cn->name = class_getconstant(c, + forward_nameandtypes->name_index, + CONSTANT_Utf8); + if (!cn->name) + return false; + + cn->descriptor = class_getconstant(c, + forward_nameandtypes->sig_index, + CONSTANT_Utf8); + if (!cn->descriptor) + return false; - Is needed by class_link for adding a VTBL to a class. All interfaces - implemented by ic are added as well. + if (opt_verify) { + /* check name */ + if (!is_valid_name_utf(cn->name)) { + *exceptionptr = + new_classformaterror(c, + "Illegal Field name \"%s\"", + cn->name->text); -*******************************************************************************/ + return false; + } -static void class_addinterface (classinfo *c, classinfo *ic) -{ - s4 j, m; - s4 i = ic->index; - vftbl *vftbl = c->vftbl; - - if (i >= vftbl->interfacetablelength) - panic ("Inernal error: interfacetable overflow"); - if (vftbl->interfacetable[-i]) - return; - - if (ic->methodscount == 0) { /* fake entry needed for subtype test */ - vftbl->interfacevftbllength[i] = 1; - vftbl->interfacetable[-i] = MNEW(methodptr, 1); - vftbl->interfacetable[-i][0] = NULL; + /* disallow referencing among others */ + if (cn->name->text[0] == '<' && cn->name != utf_init) { + *exceptionptr = + new_classformaterror(c,"Illegal reference to special method"); + return false; + } } - else { - vftbl->interfacevftbllength[i] = ic->methodscount; - vftbl->interfacetable[-i] = MNEW(methodptr, ic->methodscount); -#ifdef STATISTICS - count_vftbl_len += sizeof(methodptr) * - (ic->methodscount + (ic->methodscount == 0)); + cptags[forward_nameandtypes->thisindex] = CONSTANT_NameAndType; + cpinfos[forward_nameandtypes->thisindex] = cn; + + nfn = forward_nameandtypes; + forward_nameandtypes = forward_nameandtypes->next; + } + + while (forward_fieldmethints) { + constant_nameandtype *nat; + constant_FMIref *fmi = NEW(constant_FMIref); + +#if defined(STATISTICS) + if (opt_stat) + count_const_pool_len += sizeof(constant_FMIref); #endif + /* resolve simple name and descriptor */ - for (j=0; jmethodscount; j++) { - classinfo *sc = c; - while (sc) { - for (m = 0; m < sc->methodscount; m++) { - methodinfo *mi = &(sc->methods[m]); - if (method_canoverwrite(mi, &(ic->methods[j]))) { - vftbl->interfacetable[-i][j] = - vftbl->table[mi->vftblindex]; - goto foundmethod; - } - } - sc = sc->super; - } - foundmethod: ; - } - } + nat = class_getconstant(c, + forward_fieldmethints->nameandtype_index, + CONSTANT_NameAndType); + if (!nat) + return false; - for (j = 0; j < ic->interfacescount; j++) - class_addinterface(c, ic->interfaces[j]); -} + /* add all descriptors in {Field,Method}ref to the descriptor_pool */ + if (!descriptor_pool_add(descpool, nat->descriptor, NULL)) + return false; -/******************* Function: class_new_array ********************************* + /* the classref is created later */ - This function is called by class_new to setup an array class. + fmi->classref = (constant_classref *) (size_t) forward_fieldmethints->class_index; + fmi->name = nat->name; + fmi->descriptor = nat->descriptor; -*******************************************************************************/ + cptags[forward_fieldmethints->thisindex] = forward_fieldmethints->tag; + cpinfos[forward_fieldmethints->thisindex] = fmi; + + nff = forward_fieldmethints; + forward_fieldmethints = forward_fieldmethints->next; + } -void class_new_array(classinfo *c) -{ - classinfo *comp = NULL; - methodinfo *clone; - int namelen; + /* everything was ok */ - /* DEBUG */ /* dolog("class_new_array: %s",c->name->text); */ + return true; +} - /* Array classes are not loaded from classfiles. */ - list_remove(&unloadedclasses, c); - /* Check array class name */ - namelen = c->name->blength; - if (namelen < 2 || c->name->text[0] != '[') - panic("Invalid array class name"); - - /* Check the component type */ - switch (c->name->text[1]) { - case '[': - /* c is an array of arrays. We have to create the component class. */ - comp = class_new(utf_new(c->name->text + 1,namelen - 1)); - break; - - case 'L': - /* c is an array of objects. */ - if (namelen < 4 || c->name->text[namelen - 1] != ';') - panic("Invalid array class name"); - comp = class_new(utf_new(c->name->text + 2,namelen - 3)); - break; - } +/* load_field ****************************************************************** - /* Setup the array class */ - c->super = class_java_lang_Object; - c->flags = ACC_PUBLIC | ACC_FINAL | ACC_ABSTRACT; + Load everything about a class field from the class file and fill a + 'fieldinfo' structure. For static fields, space in the data segment + is allocated. - c->interfacescount = 2; - c->interfaces = MNEW(classinfo*,2); - c->interfaces[0] = class_java_lang_Cloneable; - c->interfaces[1] = class_java_io_Serializable; +*******************************************************************************/ - c->methodscount = 1; - c->methods = MNEW (methodinfo, c->methodscount); +#define field_load_NOVALUE 0xffffffff /* must be bigger than any u2 value! */ - clone = c->methods; - memset(clone, 0, sizeof(methodinfo)); - clone->flags = ACC_PUBLIC; - clone->name = utf_new_char("clone"); - clone->descriptor = utf_new_char("()Ljava/lang/Object;"); - clone->class = c; - clone->stubroutine = createnativestub((functionptr) &builtin_clone_array, clone); - clone->monoPoly = MONO; +static bool load_field(classbuffer *cb, fieldinfo *f, descriptor_pool *descpool) +{ + classinfo *c; + u4 attrnum, i; + u4 jtype; + u4 pindex = field_load_NOVALUE; /* constantvalue_index */ + utf *u; - /* XXX: field: length? */ + c = cb->class; - /* The array class has to be linked */ - list_addlast(&unlinkedclasses,c); - - /* - * Array classes which are created after the other classes have been - * loaded and linked are linked explicitely. - */ - c->loaded=true; - - if (loader_inited) - loader_load(c->name); /* XXX handle errors */ -} + if (!check_classbuffer_size(cb, 2 + 2 + 2)) + return false; + f->flags = suck_u2(cb); -/****************** Function: class_link_array ********************************* + if (!(u = class_getconstant(c, suck_u2(cb), CONSTANT_Utf8))) + return false; - This function is called by class_link to create the - arraydescriptor for an array class. + f->name = u; - This function returns NULL if the array cannot be linked because - the component type has not been linked yet. + if (!(u = class_getconstant(c, suck_u2(cb), CONSTANT_Utf8))) + return false; -*******************************************************************************/ + f->descriptor = u; + f->parseddesc = NULL; -static arraydescriptor *class_link_array(classinfo *c) -{ - classinfo *comp = NULL; - int namelen = c->name->blength; - arraydescriptor *desc; - vftbl *compvftbl; - - /* Check the component type */ - switch (c->name->text[1]) { - case '[': - /* c is an array of arrays. */ - comp = class_get(utf_new(c->name->text + 1,namelen - 1)); - if (!comp) panic("Could not find component array class."); - break; - - case 'L': - /* c is an array of objects. */ - comp = class_get(utf_new(c->name->text + 2,namelen - 3)); - if (!comp) panic("Could not find component class."); - break; + if (!descriptor_pool_add(descpool, u, NULL)) + return false; + + /* descriptor_pool_add accepts method descriptors, so we have to check */ + /* against them here before the call of desc_to_type below. */ + if (u->text[0] == '(') { + *exceptionptr = new_classformaterror(c,"Method descriptor used for field"); + return false; } - /* If the component type has not been linked return NULL */ - if (comp && !comp->linked) - return NULL; + if (opt_verify) { + /* check name */ + if (!is_valid_name_utf(f->name) || f->name->text[0] == '<') { + *exceptionptr = new_classformaterror(c, + "Illegal Field name \"%s\"", + f->name->text); + return false; + } - /* Allocate the arraydescriptor */ - desc = NEW(arraydescriptor); + /* check flag consistency */ + i = f->flags & (ACC_PUBLIC | ACC_PRIVATE | ACC_PROTECTED); + + if ((i != 0 && i != ACC_PUBLIC && i != ACC_PRIVATE && i != ACC_PROTECTED) || + ((f->flags & (ACC_FINAL | ACC_VOLATILE)) == (ACC_FINAL | ACC_VOLATILE))) { + *exceptionptr = + new_classformaterror(c, + "Illegal field modifiers: 0x%X", + f->flags); + return false; + } - if (comp) { - /* c is an array of references */ - desc->arraytype = ARRAYTYPE_OBJECT; - desc->componentsize = sizeof(void*); - desc->dataoffset = OFFSET(java_objectarray,data); + if (c->flags & ACC_INTERFACE) { + if (((f->flags & (ACC_STATIC | ACC_PUBLIC | ACC_FINAL)) + != (ACC_STATIC | ACC_PUBLIC | ACC_FINAL)) || + f->flags & ACC_TRANSIENT) { + *exceptionptr = + new_classformaterror(c, + "Illegal field modifiers: 0x%X", + f->flags); + return false; + } + } + } - compvftbl = comp->vftbl; - if (!compvftbl) - panic("Component class has no vftbl"); - desc->componentvftbl = compvftbl; + f->type = jtype = desc_to_type(f->descriptor); /* data type */ + f->offset = 0; /* offset from start of object */ + f->class = c; + f->xta = NULL; + + switch (f->type) { + case TYPE_INT: f->value.i = 0; break; + case TYPE_FLOAT: f->value.f = 0.0; break; + case TYPE_DOUBLE: f->value.d = 0.0; break; + case TYPE_ADDRESS: f->value.a = NULL; break; + case TYPE_LONG: +#if U8_AVAILABLE + f->value.l = 0; break; +#else + f->value.l.low = 0; f->value.l.high = 0; break; +#endif + } + + /* read attributes */ + if (!check_classbuffer_size(cb, 2)) + return false; + + attrnum = suck_u2(cb); + for (i = 0; i < attrnum; i++) { + if (!check_classbuffer_size(cb, 2)) + return false; + + if (!(u = class_getconstant(c, suck_u2(cb), CONSTANT_Utf8))) + return false; + + if (u == utf_ConstantValue) { + if (!check_classbuffer_size(cb, 4 + 2)) + return false; + + /* check attribute length */ + if (suck_u4(cb) != 2) { + *exceptionptr = + new_classformaterror(c, "Wrong size for VALUE attribute"); + return false; + } + + /* constant value attribute */ + if (pindex != field_load_NOVALUE) { + *exceptionptr = + new_classformaterror(c, + "Multiple ConstantValue attributes"); + return false; + } + + /* index of value in constantpool */ + pindex = suck_u2(cb); - if (compvftbl->arraydesc) { - desc->elementvftbl = compvftbl->arraydesc->elementvftbl; - if (compvftbl->arraydesc->dimension >= 255) - panic("Creating array of dimension >255"); - desc->dimension = compvftbl->arraydesc->dimension + 1; - desc->elementtype = compvftbl->arraydesc->elementtype; - } - else { - desc->elementvftbl = compvftbl; - desc->dimension = 1; - desc->elementtype = ARRAYTYPE_OBJECT; - } + /* initialize field with value from constantpool */ + switch (jtype) { + case TYPE_INT: { + constant_integer *ci; - } else { - /* c is an array of a primitive type */ - switch (c->name->text[1]) { - case 'Z': desc->arraytype = ARRAYTYPE_BOOLEAN; - desc->dataoffset = OFFSET(java_booleanarray,data); - desc->componentsize = sizeof(u1); - break; + if (!(ci = class_getconstant(c, pindex, CONSTANT_Integer))) + return false; - case 'B': desc->arraytype = ARRAYTYPE_BYTE; - desc->dataoffset = OFFSET(java_bytearray,data); - desc->componentsize = sizeof(u1); + f->value.i = ci->value; + } break; + + case TYPE_LONG: { + constant_long *cl; - case 'C': desc->arraytype = ARRAYTYPE_CHAR; - desc->dataoffset = OFFSET(java_chararray,data); - desc->componentsize = sizeof(u2); - break; + if (!(cl = class_getconstant(c, pindex, CONSTANT_Long))) + return false; - case 'D': desc->arraytype = ARRAYTYPE_DOUBLE; - desc->dataoffset = OFFSET(java_doublearray,data); - desc->componentsize = sizeof(double); + f->value.l = cl->value; + } break; - case 'F': desc->arraytype = ARRAYTYPE_FLOAT; - desc->dataoffset = OFFSET(java_floatarray,data); - desc->componentsize = sizeof(float); - break; + case TYPE_FLOAT: { + constant_float *cf; - case 'I': desc->arraytype = ARRAYTYPE_INT; - desc->dataoffset = OFFSET(java_intarray,data); - desc->componentsize = sizeof(s4); - break; + if (!(cf = class_getconstant(c, pindex, CONSTANT_Float))) + return false; - case 'J': desc->arraytype = ARRAYTYPE_LONG; - desc->dataoffset = OFFSET(java_longarray,data); - desc->componentsize = sizeof(s8); + f->value.f = cf->value; + } break; + + case TYPE_DOUBLE: { + constant_double *cd; - case 'S': desc->arraytype = ARRAYTYPE_SHORT; - desc->dataoffset = OFFSET(java_shortarray,data); - desc->componentsize = sizeof(s2); + if (!(cd = class_getconstant(c, pindex, CONSTANT_Double))) + return false; + + f->value.d = cd->value; + } break; + + case TYPE_ADDRESS: + if (!(u = class_getconstant(c, pindex, CONSTANT_String))) + return false; - default: - panic("Invalid array class name"); + /* create javastring from compressed utf8-string */ + f->value.a = literalstring_new(u); + break; + + default: + log_text("Invalid Constant - Type"); + } + + } else { + /* unknown attribute */ + if (!skipattributebody(cb)) + return false; } - - desc->componentvftbl = NULL; - desc->elementvftbl = NULL; - desc->dimension = 1; - desc->elementtype = desc->arraytype; } - return desc; + /* everything was ok */ + + return true; } -/********************** Function: class_link *********************************** +/* load_method ***************************************************************** - Tries to link a class. The super class and every implemented interface must - already have been linked. The function calculates the length in bytes that - an instance of this class requires as well as the VTBL for methods and - interface methods. + Loads a method from the class file and fills an existing + 'methodinfo' structure. For native methods, the function pointer + field is set to the real function pointer, for JavaVM methods a + pointer to the compiler is used preliminarily. - If the class can be linked, it is removed from the list 'unlinkedclasses' - and added to 'linkedclasses'. Otherwise, it is moved to the end of - 'unlinkedclasses'. - - Attention: If cyclical class definitions are encountered, the program gets - into an infinite loop (we'll have to work that out) - *******************************************************************************/ -void class_link(classinfo *c) +static bool load_method(classbuffer *cb, methodinfo *m, descriptor_pool *descpool) { - s4 supervftbllength; /* vftbllegnth of super class */ - s4 vftbllength; /* vftbllength of current class */ - s4 interfacetablelength; /* interface table length */ - classinfo *super = c->super; /* super class */ - classinfo *ic, *c2; /* intermediate class variables */ - vftbl *v; /* vftbl of current class */ - s4 i; /* interface/method/field counter */ - arraydescriptor *arraydesc = NULL; /* descriptor for array classes */ + classinfo *c; + int argcount; + s4 i, j; + u4 attrnum; + u4 codeattrnum; + utf *u; + c = cb->class; - /* check if all superclasses are already linked, if not put c at end of - unlinked list and return. Additionally initialize class fields. */ +#if defined(USE_THREADS) && defined(NATIVE_THREADS) + initObjectLock(&m->header); +#endif - /* check interfaces */ +#ifdef STATISTICS + if (opt_stat) + count_all_methods++; +#endif - for (i = 0; i < c->interfacescount; i++) { - ic = c->interfaces[i]; - if (!ic->linked) { - list_remove(&unlinkedclasses, c); - list_addlast(&unlinkedclasses, c); - return; - } - if ((ic->flags & ACC_INTERFACE) == 0) { - dolog("Specified interface is not declared as interface:"); - log_utf(ic->name); - dolog("in"); - log_utf(c->name); - panic("Specified interface is not declared as interface"); - } - } + m->thrownexceptionscount = 0; + m->linenumbercount = 0; + m->linenumbers = 0; + m->class = c; + m->nativelyoverloaded = false; - /* check super class */ - - if (super == NULL) { /* class java.long.Object */ - c->index = 0; - c->classUsed = USED; /* Object class is always used CO-RT*/ - c->impldBy = NULL; - c->instancesize = sizeof(java_objectheader); - - vftbllength = supervftbllength = 0; - - c->finalizer = NULL; - - } else { - if (!super->linked) { - list_remove(&unlinkedclasses, c); - list_addlast(&unlinkedclasses, c); - return; - } + if (!check_classbuffer_size(cb, 2 + 2 + 2)) + return false; - if ((super->flags & ACC_INTERFACE) != 0) - panic("Interface specified as super class"); + m->flags = suck_u2(cb); - /* handle array classes */ - /* The component class must have been linked already. */ - if (c->name->text[0] == '[') - if ((arraydesc = class_link_array(c)) == NULL) { - list_remove(&unlinkedclasses, c); - list_addlast(&unlinkedclasses, c); - return; - } + if (!(u = class_getconstant(c, suck_u2(cb), CONSTANT_Utf8))) + return false; - /* Don't allow extending final classes */ - if ((super->flags & ACC_FINAL) != 0) - panic("Trying to extend final class"); - - if (c->flags & ACC_INTERFACE) - c->index = interfaceindex++; - else - c->index = super->index + 1; - - c->instancesize = super->instancesize; - - vftbllength = supervftbllength = super->vftbl->vftbllength; - - c->finalizer = super->finalizer; - } + m->name = u; + if (!(u = class_getconstant(c, suck_u2(cb), CONSTANT_Utf8))) + return false; - if (linkverbose) { - char logtext[MAXLOGTEXT]; - sprintf(logtext, "Linking Class: "); - utf_sprint(logtext + strlen(logtext), c->name ); - log_text(logtext); - } + m->descriptor = u; + m->parseddesc = NULL; - /* compute vftbl length */ + if (!descriptor_pool_add(descpool, u, &argcount)) + return false; - for (i = 0; i < c->methodscount; i++) { - methodinfo *m = &(c->methods[i]); - - if (!(m->flags & ACC_STATIC)) { /* is instance method */ - classinfo *sc = super; - while (sc) { - int j; - for (j = 0; j < sc->methodscount; j++) { - if (method_canoverwrite(m, &(sc->methods[j]))) { - if ((sc->methods[j].flags & ACC_PRIVATE) != 0) - goto notfoundvftblindex; - if ((sc->methods[j].flags & ACC_FINAL) != 0) { - log_utf(c->name); - log_utf(sc->name); - log_utf(sc->methods[j].name); - log_utf(sc->methods[j].descriptor); - panic("Trying to overwrite final method"); - } - m->vftblindex = sc->methods[j].vftblindex; - goto foundvftblindex; - } - } - sc = sc->super; - } - notfoundvftblindex: - m->vftblindex = (vftbllength++); - foundvftblindex: ; + if (opt_verify) { + if (!is_valid_name_utf(m->name)) { + *exceptionptr = new_classformaterror(c,"Method with invalid name"); + return false; } - } - -#ifdef STATISTICS - count_vftbl_len += sizeof(vftbl) + (sizeof(methodptr) * (vftbllength - 1)); -#endif - - /* compute interfacetable length */ - interfacetablelength = 0; - c2 = c; - while (c2) { - for (i = 0; i < c2->interfacescount; i++) { - s4 h = class_highestinterface (c2->interfaces[i]) + 1; - if (h > interfacetablelength) - interfacetablelength = h; + if (m->name->text[0] == '<' && + m->name != utf_init && m->name != utf_clinit) { + *exceptionptr = new_classformaterror(c,"Method with invalid special name"); + return false; } - c2 = c2->super; } + + if (!(m->flags & ACC_STATIC)) + argcount++; /* count the 'this' argument */ - /* allocate virtual function table */ + if (opt_verify) { + if (argcount > 255) { + *exceptionptr = + new_classformaterror(c, "Too many arguments in signature"); + return false; + } - v = (vftbl*) mem_alloc(sizeof(vftbl) + sizeof(methodptr) * - (vftbllength - 1) + sizeof(methodptr*) * - (interfacetablelength - (interfacetablelength > 0))); - v = (vftbl*) (((methodptr*) v) + (interfacetablelength - 1) * - (interfacetablelength > 1)); - c->header.vftbl = c->vftbl = v; - v->class = c; - v->vftbllength = vftbllength; - v->interfacetablelength = interfacetablelength; - v->arraydesc = arraydesc; + /* check flag consistency */ + if (m->name != utf_clinit) { + i = (m->flags & (ACC_PUBLIC | ACC_PRIVATE | ACC_PROTECTED)); - /* store interface index in vftbl */ - if (c->flags & ACC_INTERFACE) - v->baseval = -(c->index); + if (i != 0 && i != ACC_PUBLIC && i != ACC_PRIVATE && i != ACC_PROTECTED) { + *exceptionptr = + new_classformaterror(c, + "Illegal method modifiers: 0x%X", + m->flags); + return false; + } - /* copy virtual function table of super class */ + if (m->flags & ACC_ABSTRACT) { + if ((m->flags & (ACC_FINAL | ACC_NATIVE | ACC_PRIVATE | + ACC_STATIC | ACC_STRICT | ACC_SYNCHRONIZED))) { + *exceptionptr = + new_classformaterror(c, + "Illegal method modifiers: 0x%X", + m->flags); + return false; + } + } - for (i = 0; i < supervftbllength; i++) - v->table[i] = super->vftbl->table[i]; - - /* add method stubs into virtual function table */ + if (c->flags & ACC_INTERFACE) { + if ((m->flags & (ACC_ABSTRACT | ACC_PUBLIC)) != (ACC_ABSTRACT | ACC_PUBLIC)) { + *exceptionptr = + new_classformaterror(c, + "Illegal method modifiers: 0x%X", + m->flags); + return false; + } + } - for (i = 0; i < c->methodscount; i++) { - methodinfo *m = &(c->methods[i]); - if (!(m->flags & ACC_STATIC)) { - v->table[m->vftblindex] = m->stubroutine; + if (m->name == utf_init) { + if (m->flags & (ACC_STATIC | ACC_FINAL | ACC_SYNCHRONIZED | + ACC_NATIVE | ACC_ABSTRACT)) { + *exceptionptr = new_classformaterror(c, + "Instance initialization method has invalid flags set"); + return false; + } + } } } - - /* compute instance size and offset of each field */ - - for (i = 0; i < c->fieldscount; i++) { - s4 dsize; - fieldinfo *f = &(c->fields[i]); - if (!(f->flags & ACC_STATIC) ) { - dsize = desc_typesize(f->descriptor); - c->instancesize = ALIGN(c->instancesize, dsize); - f->offset = c->instancesize; - c->instancesize += dsize; - } - } - - /* initialize interfacetable and interfacevftbllength */ - - v->interfacevftbllength = MNEW(s4, interfacetablelength); + m->jcode = NULL; + m->basicblockcount = 0; + m->basicblocks = NULL; + m->basicblockindex = NULL; + m->instructioncount = 0; + m->instructions = NULL; + m->stackcount = 0; + m->stack = NULL; + m->exceptiontable = NULL; + m->stubroutine = NULL; + m->mcode = NULL; + m->entrypoint = NULL; + m->methodUsed = NOTUSED; + m->monoPoly = MONO; + m->subRedefs = 0; + m->subRedefsUsed = 0; -#ifdef STATISTICS - count_vftbl_len += (4 + sizeof(s4)) * v->interfacetablelength; -#endif + m->xta = NULL; - for (i = 0; i < interfacetablelength; i++) { - v->interfacevftbllength[i] = 0; - v->interfacetable[-i] = NULL; - } - - /* add interfaces */ + if (!check_classbuffer_size(cb, 2)) + return false; - for (c2 = c; c2 != NULL; c2 = c2->super) - for (i = 0; i < c2->interfacescount; i++) { - class_addinterface(c, c2->interfaces[i]); - } + attrnum = suck_u2(cb); + for (i = 0; i < attrnum; i++) { + utf *aname; - /* add finalizer method (not for java.lang.Object) */ + if (!check_classbuffer_size(cb, 2)) + return false; - if (super != NULL) { - methodinfo *fi; - static utf *finame = NULL; - static utf *fidesc = NULL; + if (!(aname = class_getconstant(c, suck_u2(cb), CONSTANT_Utf8))) + return false; - if (finame == NULL) - finame = utf_finalize; - if (fidesc == NULL) - fidesc = utf_fidesc; + if (aname == utf_Code) { + if (m->flags & (ACC_ABSTRACT | ACC_NATIVE)) { + *exceptionptr = + new_classformaterror(c, + "Code attribute in native or abstract methods"); - fi = class_findmethod(c, finame, fidesc); - if (fi != NULL) { - if (!(fi->flags & ACC_STATIC)) { - c->finalizer = fi; + return false; } - } - } + + if (m->jcode) { + *exceptionptr = + new_classformaterror(c, "Multiple Code attributes"); - /* final tasks */ + return false; + } - c->linked = true; + if (!check_classbuffer_size(cb, 4 + 2 + 2)) + return false; - list_remove(&unlinkedclasses, c); - list_addlast(&linkedclasses, c); -} + suck_u4(cb); + m->maxstack = suck_u2(cb); + m->maxlocals = suck_u2(cb); + if (m->maxlocals < argcount) { + *exceptionptr = + new_classformaterror(c, "Arguments can't fit into locals"); -/******************* Function: class_freepool ********************************** + return false; + } + + if (!check_classbuffer_size(cb, 4)) + return false; - Frees all resources used by this classes Constant Pool. + m->jcodelength = suck_u4(cb); -*******************************************************************************/ + if (m->jcodelength == 0) { + *exceptionptr = + new_classformaterror(c, "Code of a method has length 0"); -static void class_freecpool (classinfo *c) -{ - u4 idx; - u4 tag; - voidptr info; - - for (idx=0; idx < c->cpcount; idx++) { - tag = c->cptags[idx]; - info = c->cpinfos[idx]; - - if (info != NULL) { - switch (tag) { - case CONSTANT_Fieldref: - case CONSTANT_Methodref: - case CONSTANT_InterfaceMethodref: - FREE (info, constant_FMIref); - break; - case CONSTANT_Integer: - FREE (info, constant_integer); - break; - case CONSTANT_Float: - FREE (info, constant_float); - break; - case CONSTANT_Long: - FREE (info, constant_long); - break; - case CONSTANT_Double: - FREE (info, constant_double); - break; - case CONSTANT_NameAndType: - FREE (info, constant_nameandtype); - break; + return false; } + + if (m->jcodelength > 65535) { + *exceptionptr = + new_classformaterror(c, + "Code of a method longer than 65535 bytes"); + + return false; } - } - MFREE (c -> cptags, u1, c -> cpcount); - MFREE (c -> cpinfos, voidptr, c -> cpcount); -} + if (!check_classbuffer_size(cb, m->jcodelength)) + return false; + m->jcode = MNEW(u1, m->jcodelength); + suck_nbytes(m->jcode, cb, m->jcodelength); -/*********************** Function: class_free ********************************** + if (!check_classbuffer_size(cb, 2)) + return false; - Frees all resources used by the class. + m->exceptiontablelength = suck_u2(cb); + if (!check_classbuffer_size(cb, (2 + 2 + 2 + 2) * m->exceptiontablelength)) + return false; -*******************************************************************************/ + m->exceptiontable = MNEW(exceptiontable, m->exceptiontablelength); -static void class_free(classinfo *c) -{ - s4 i; - vftbl *v; - - class_freecpool(c); +#if defined(STATISTICS) + if (opt_stat) { + count_vmcode_len += m->jcodelength + 18; + count_extable_len += + m->exceptiontablelength * sizeof(exceptiontable); + } +#endif - MFREE(c->interfaces, classinfo*, c->interfacescount); + for (j = 0; j < m->exceptiontablelength; j++) { + u4 idx; + m->exceptiontable[j].startpc = suck_u2(cb); + m->exceptiontable[j].endpc = suck_u2(cb); + m->exceptiontable[j].handlerpc = suck_u2(cb); - for (i = 0; i < c->fieldscount; i++) - field_free(&(c->fields[i])); - - for (i = 0; i < c->methodscount; i++) - method_free(&(c->methods[i])); - MFREE(c->methods, methodinfo, c->methodscount); + idx = suck_u2(cb); + if (!idx) { + m->exceptiontable[j].catchtype.any = NULL; - if ((v = c->vftbl) != NULL) { - if (v->arraydesc) - mem_free(v->arraydesc,sizeof(arraydescriptor)); - - for (i = 0; i < v->interfacetablelength; i++) { - MFREE(v->interfacetable[-i], methodptr, v->interfacevftbllength[i]); - } - MFREE(v->interfacevftbllength, s4, v->interfacetablelength); - - i = sizeof(vftbl) + sizeof(methodptr) * (v->vftbllength - 1) + - sizeof(methodptr*) * (v->interfacetablelength - - (v->interfacetablelength > 0)); - v = (vftbl*) (((methodptr*) v) - (v->interfacetablelength - 1) * - (v->interfacetablelength > 1)); - mem_free(v, i); - } + } else { + /* the classref is created later */ + if (!(m->exceptiontable[j].catchtype.any = + (utf*)class_getconstant(c, idx, CONSTANT_Class))) + return false; + } + } - if (c->innerclasscount) - MFREE(c->innerclass, innerclassinfo, c->innerclasscount); + if (!check_classbuffer_size(cb, 2)) + return false; - /* if (c->classvftbl) - mem_free(c->header.vftbl, sizeof(vftbl) + sizeof(methodptr)*(c->vftbl->vftbllength-1)); */ - - GCFREE(c); -} + codeattrnum = suck_u2(cb); + for (; codeattrnum > 0; codeattrnum--) { + utf *caname; -/************************* Function: class_findfield *************************** - - Searches a 'classinfo' structure for a field having the given name and - type. + if (!check_classbuffer_size(cb, 2)) + return false; -*******************************************************************************/ + if (!(caname = class_getconstant(c, suck_u2(cb), CONSTANT_Utf8))) + return false; -fieldinfo *class_findfield(classinfo *c, utf *name, utf *desc) -{ - s4 i; - - for (i = 0; i < c->fieldscount; i++) { - if ((c->fields[i].name == name) && (c->fields[i].descriptor == desc)) - return &(c->fields[i]); - } + if (caname == utf_LineNumberTable) { + u2 lncid; - panic("Can not find field given in CONSTANT_Fieldref"); + if (!check_classbuffer_size(cb, 4 + 2)) + return false; - /* keep compiler happy */ - return NULL; -} + suck_u4(cb); + m->linenumbercount = suck_u2(cb); + if (!check_classbuffer_size(cb, + (2 + 2) * m->linenumbercount)) + return false; -/************************* Function: class_findmethod ************************** - - Searches a 'classinfo' structure for a method having the given name and - type and returns the index in the class info structure. - If type is NULL, it is ignored. + m->linenumbers = MNEW(lineinfo, m->linenumbercount); + + for (lncid = 0; lncid < m->linenumbercount; lncid++) { + m->linenumbers[lncid].start_pc = suck_u2(cb); + m->linenumbers[lncid].line_number = suck_u2(cb); + } + codeattrnum--; -*******************************************************************************/ + if (!skipattributes(cb, codeattrnum)) + return false; + + break; -s4 class_findmethodIndex(classinfo *c, utf *name, utf *desc) -{ - s4 i; -#if defined(JOWENN_DEBUG1) || defined(JOWENN_DEBUG2) - char *buffer; - int buffer_len, pos; -#endif -#ifdef JOWENN_DEBUG1 + } else { + if (!skipattributebody(cb)) + return false; + } + } - buffer_len = - utf_strlen(name) + utf_strlen(desc) + utf_strlen(c->name) + 64; - - buffer = MNEW(char, buffer_len); - - strcpy(buffer, "class_findmethod: method:"); - utf_sprint(buffer + strlen(buffer), name); - strcpy(buffer + strlen(buffer), ", desc: "); - utf_sprint(buffer + strlen(buffer), desc); - strcpy(buffer + strlen(buffer), ", classname: "); - utf_sprint(buffer + strlen(buffer), c->name); - - log_text(buffer); + } else if (aname == utf_Exceptions) { + s4 j; - MFREE(buffer, char, buffer_len); -#endif - for (i = 0; i < c->methodscount; i++) { -#ifdef JOWENN_DEBUG2 - buffer_len = - utf_strlen(c->methods[i].name) + utf_strlen(c->methods[i].descriptor)+ 64; - - buffer = MNEW(char, buffer_len); + if (m->thrownexceptions) { + *exceptionptr = + new_classformaterror(c, "Multiple Exceptions attributes"); + return false; + } - strcpy(buffer, "class_findmethod: comparing to method:"); - utf_sprint(buffer + strlen(buffer), c->methods[i].name); - strcpy(buffer + strlen(buffer), ", desc: "); - utf_sprint(buffer + strlen(buffer), c->methods[i].descriptor); - - log_text(buffer); + if (!check_classbuffer_size(cb, 4 + 2)) + return false; - MFREE(buffer, char, buffer_len); -#endif - - - if ((c->methods[i].name == name) && ((desc == NULL) || - (c->methods[i].descriptor == desc))) { - return i; + suck_u4(cb); /* length */ + m->thrownexceptionscount = suck_u2(cb); + + if (!check_classbuffer_size(cb, 2 * m->thrownexceptionscount)) + return false; + + m->thrownexceptions = MNEW(classref_or_classinfo, m->thrownexceptionscount); + + for (j = 0; j < m->thrownexceptionscount; j++) { + /* the classref is created later */ + if (!((m->thrownexceptions)[j].any = + (utf*) class_getconstant(c, suck_u2(cb), CONSTANT_Class))) + return false; + } + + } else { + if (!skipattributebody(cb)) + return false; } } -#ifdef JOWENN_DEBUG2 - class_showconstantpool(c); - log_text("class_findmethod: returning NULL"); -#endif + if (!m->jcode && !(m->flags & (ACC_ABSTRACT | ACC_NATIVE))) { + *exceptionptr = new_classformaterror(c, "Missing Code attribute"); + + return false; + } - return -1; + /* everything was ok */ + + return true; } -/************************* Function: class_findmethod ************************** - - Searches a 'classinfo' structure for a method having the given name and - type. - If type is NULL, it is ignored. +/* load_attribute ************************************************************** + Read attributes from classfile. + *******************************************************************************/ -methodinfo *class_findmethod(classinfo *c, utf *name, utf *desc) +static bool load_attributes(classbuffer *cb, u4 num) { -#if 0 - s4 i; -#if defined(JOWENN_DEBUG1) || defined(JOWENN_DEBUG2) - char *buffer; - int buffer_len, pos; -#endif -#ifdef JOWENN_DEBUG1 + classinfo *c; + utf *aname; + u4 i, j; - buffer_len = - utf_strlen(name) + utf_strlen(desc) + utf_strlen(c->name) + 64; - - buffer = MNEW(char, buffer_len); - - strcpy(buffer, "class_findmethod: method:"); - utf_sprint(buffer + strlen(buffer), name); - strcpy(buffer + strlen(buffer), ", desc: "); - utf_sprint(buffer + strlen(buffer), desc); - strcpy(buffer + strlen(buffer), ", classname: "); - utf_sprint(buffer + strlen(buffer), c->name); - - log_text(buffer); + c = cb->class; - MFREE(buffer, char, buffer_len); -#endif - for (i = 0; i < c->methodscount; i++) { -#ifdef JOWENN_DEBUG2 - buffer_len = - utf_strlen(c->methods[i].name) + utf_strlen(c->methods[i].descriptor)+ 64; - - buffer = MNEW(char, buffer_len); + for (i = 0; i < num; i++) { + /* retrieve attribute name */ + if (!check_classbuffer_size(cb, 2)) + return false; - strcpy(buffer, "class_findmethod: comparing to method:"); - utf_sprint(buffer + strlen(buffer), c->methods[i].name); - strcpy(buffer + strlen(buffer), ", desc: "); - utf_sprint(buffer + strlen(buffer), c->methods[i].descriptor); - - log_text(buffer); + if (!(aname = class_getconstant(c, suck_u2(cb), CONSTANT_Utf8))) + return false; - MFREE(buffer, char, buffer_len); -#endif - - if ((c->methods[i].name == name) && ((desc == NULL) || - (c->methods[i].descriptor == desc))) { - return &(c->methods[i]); - } - } -#ifdef JOWENN_DEBUG2 - class_showconstantpool(c); - log_text("class_findmethod: returning NULL"); -#endif - return NULL; -#endif + if (aname == utf_InnerClasses) { + /* innerclasses attribute */ + if (c->innerclass) { + *exceptionptr = + new_classformaterror(c, "Multiple InnerClasses attributes"); + return false; + } + + if (!check_classbuffer_size(cb, 4 + 2)) + return false; - s4 idx=class_findmethodIndex(c, name, desc); -/* if (idx==-1) log_text("class_findmethod: method not found");*/ - if (idx == -1) return NULL; + /* skip attribute length */ + suck_u4(cb); - return &(c->methods[idx]); -} + /* number of records */ + c->innerclasscount = suck_u2(cb); + if (!check_classbuffer_size(cb, (2 + 2 + 2 + 2) * c->innerclasscount)) + return false; -/*********************** Function: class_fetchmethod ************************** - - like class_findmethod, but aborts with an error if the method is not found + /* allocate memory for innerclass structure */ + c->innerclass = MNEW(innerclassinfo, c->innerclasscount); -*******************************************************************************/ + for (j = 0; j < c->innerclasscount; j++) { + /* The innerclass structure contains a class with an encoded + name, its defining scope, its simple name and a bitmask of + the access flags. If an inner class is not a member, its + outer_class is NULL, if a class is anonymous, its name is + NULL. */ + + innerclassinfo *info = c->innerclass + j; -methodinfo *class_fetchmethod(classinfo *c, utf *name, utf *desc) -{ - methodinfo *mi; - mi = class_findmethod(c, name, desc); - - if (!mi) { - log_plain("Class: "); if (c) log_plain_utf(c->name); log_nl(); - log_plain("Method: "); if (name) log_plain_utf(name); log_nl(); - log_plain("Descriptor: "); if (desc) log_plain_utf(desc); log_nl(); - panic("Method not found"); + info->inner_class.ref = + innerclass_getconstant(c, suck_u2(cb), CONSTANT_Class); + info->outer_class.ref = + innerclass_getconstant(c, suck_u2(cb), CONSTANT_Class); + info->name = + innerclass_getconstant(c, suck_u2(cb), CONSTANT_Utf8); + info->flags = suck_u2(cb); + } + + } else if (aname == utf_SourceFile) { + if (!check_classbuffer_size(cb, 4 + 2)) + return false; + + if (suck_u4(cb) != 2) { + *exceptionptr = + new_classformaterror(c, "Wrong size for VALUE attribute"); + return false; + } + + if (c->sourcefile) { + *exceptionptr = + new_classformaterror(c, "Multiple SourceFile attributes"); + return false; + } + + if (!(c->sourcefile = class_getconstant(c, suck_u2(cb), CONSTANT_Utf8))) + return false; + + } else { + /* unknown attribute */ + if (!skipattributebody(cb)) + return false; + } } - return mi; + return true; } -/*********************** Function: class_findmethod_w************************** +/* load_class_from_sysloader *************************************************** + + Load the class with the given name using the system class loader + + IN: + name.............the classname - like class_findmethod, but logs a warning if the method is not found + RETURN VALUE: + the loaded class, or + NULL if an exception has been thrown *******************************************************************************/ -methodinfo *class_findmethod_w(classinfo *c, utf *name, utf *desc, char *from) +classinfo *load_class_from_sysloader(utf *name) { - methodinfo *mi; - mi = class_findmethod(c, name, desc); - - if (!mi) { - log_plain("Class: "); if (c) log_plain_utf(c->name); log_nl(); - log_plain("Method: "); if (name) log_plain_utf(name); log_nl(); - log_plain("Descriptor: "); if (desc) log_plain_utf(desc); log_nl(); - - if ( c->flags & ACC_PUBLIC ) log_plain(" PUBLIC "); - if ( c->flags & ACC_PRIVATE ) log_plain(" PRIVATE "); - if ( c->flags & ACC_PROTECTED ) log_plain(" PROTECTED "); - if ( c->flags & ACC_STATIC ) log_plain(" STATIC "); - if ( c->flags & ACC_FINAL ) log_plain(" FINAL "); - if ( c->flags & ACC_SYNCHRONIZED ) log_plain(" SYNCHRONIZED "); - if ( c->flags & ACC_VOLATILE ) log_plain(" VOLATILE "); - if ( c->flags & ACC_TRANSIENT ) log_plain(" TRANSIENT "); - if ( c->flags & ACC_NATIVE ) log_plain(" NATIVE "); - if ( c->flags & ACC_INTERFACE ) log_plain(" INTERFACE "); - if ( c->flags & ACC_ABSTRACT ) log_plain(" ABSTRACT "); - - log_plain(from); - log_plain(" : WARNING: Method not found");log_nl( ); - } - - return mi; -} + methodinfo *m; + java_objectheader *cl; + classinfo *r; +#ifdef LOADER_VERBOSE + char logtext[MAXLOGTEXT]; + LOADER_INDENT(logtext); + sprintf(logtext+strlen(logtext),"load_class_from_sysloader("); + utf_sprint(logtext+strlen(logtext),name);strcat(logtext,")"); + log_text(logtext); +#endif -/************************* Function: class_findmethod_approx ****************** + LOADER_ASSERT(class_java_lang_Object); + LOADER_ASSERT(class_java_lang_ClassLoader); + LOADER_ASSERT(class_java_lang_ClassLoader->linked); - like class_findmethod but ignores the return value when comparing the - descriptor. + m = class_resolveclassmethod(class_java_lang_ClassLoader, + utf_getSystemClassLoader, + utf_void__java_lang_ClassLoader, + class_java_lang_Object, + false); -*******************************************************************************/ + if (!m) + return false; -methodinfo *class_findmethod_approx(classinfo *c, utf *name, utf *desc) -{ - s4 i; + cl = (java_objectheader *) asm_calljavafunction(m, NULL, NULL, NULL, NULL); + if (!cl) + return false; - for (i = 0; i < c->methodscount; i++) { - if (c->methods[i].name == name) { - utf *meth_descr = c->methods[i].descriptor; - - if (desc == NULL) - /* ignore type */ - return &(c->methods[i]); - - if (desc->blength <= meth_descr->blength) { - /* current position in utf text */ - char *desc_utf_ptr = desc->text; - char *meth_utf_ptr = meth_descr->text; - /* points behind utf strings */ - char *desc_end = utf_end(desc); - char *meth_end = utf_end(meth_descr); - char ch; - - /* compare argument types */ - while (desc_utf_ptr < desc_end && meth_utf_ptr < meth_end) { - - if ((ch = *desc_utf_ptr++) != (*meth_utf_ptr++)) - break; /* no match */ - - if (ch == ')') - return &(c->methods[i]); /* all parameter types equal */ - } - } - } - } + LOADER_INC(); + r = load_class_from_classloader(name, cl); + LOADER_DEC(); - return NULL; + return r; } +/* load_class_from_classloader ************************************************* -/***************** Function: class_resolvemethod_approx *********************** - - Searches a class and every super class for a method (without paying - attention to the return value) + Load the class with the given name using the given user-defined class loader. + + IN: + name.............the classname + cl...............user-defined class loader + + RETURN VALUE: + the loaded class, or + NULL if an exception has been thrown *******************************************************************************/ -methodinfo *class_resolvemethod_approx(classinfo *c, utf *name, utf *desc) +classinfo *load_class_from_classloader(utf *name, java_objectheader *cl) { - while (c) { - /* search for method (ignore returntype) */ - methodinfo *m = class_findmethod_approx(c, name, desc); - /* method found */ - if (m) return m; - /* search superclass */ - c = c->super; - } - - return NULL; -} + classinfo *r; +#ifdef LOADER_VERBOSE + char logtext[MAXLOGTEXT]; + LOADER_INDENT(logtext); + strcat(logtext,"load_class_from_classloader("); + utf_sprint(logtext+strlen(logtext),name);sprintf(logtext+strlen(logtext),",%p,",(void*)cl); + if (!cl) strcat(logtext,""); + else if (cl->vftbl && cl->vftbl->class) utf_sprint(logtext+strlen(logtext),cl->vftbl->class->name); + else strcat(logtext,""); + strcat(logtext,")"); + log_text(logtext); +#endif -/************************* Function: class_resolvemethod *********************** - - Searches a class and every super class for a method. + LOADER_ASSERT(name); -*******************************************************************************/ + /* lookup if this class has already been loaded */ -methodinfo *class_resolvemethod(classinfo *c, utf *name, utf *desc) -{ - while (c) { - methodinfo *m = class_findmethod(c, name, desc); - if (m) return m; - /* search superclass */ - c = c->super; - } + r = classcache_lookup(cl, name); - return NULL; -} +#ifdef LOADER_VERBOSE + if (r) + dolog(" cached -> %p",(void*)r); +#endif + if (r) + return r; -/************************* Function: class_issubclass ************************** + /* if other class loader than bootstrap, call it */ - Checks if sub is a descendant of super. - -*******************************************************************************/ + if (cl) { + methodinfo *lc; + char *text; + s4 namelen; -bool class_issubclass(classinfo *sub, classinfo *super) -{ - for (;;) { - if (!sub) return false; - if (sub == super) return true; - sub = sub->super; - } -} + text = name->text; + namelen = name->blength; + /* handle array classes */ + if (text[0] == '[') { + classinfo *comp; + utf *u; + + switch (text[1]) { + case 'L': + /* check for cases like `[L;' or `[L[I;' or `[Ljava.lang.Object' */ + if (namelen < 4 || text[2] == '[' || text[namelen - 1] != ';') { + *exceptionptr = new_noclassdeffounderror(name); + return false; + } -/****************** Initialization function for classes ****************** + u = utf_new(text + 2, namelen - 3); - In Java, every class can have a static initialization function. This - function has to be called BEFORE calling other methods or accessing static - variables. + if (!(comp = load_class_from_classloader(u, cl))) + return false; -*******************************************************************************/ + /* create the array class */ + return class_array_of(comp, false); -void class_init(classinfo *c) -{ - methodinfo *m; - native_stackframeinfo **info; - s4 i; -#if defined(USE_THREADS) && !defined(NATIVE_THREADS) - int b; -#endif + case '[': + /* load the component class */ - if (!makeinitializations) - return; - if (c->initialized) - return; + u = utf_new(text + 1, namelen - 1); - c->initialized = true; + if (!(comp = load_class_from_classloader(u, cl))) + return false; -#ifdef STATISTICS - count_class_inits++; -#endif + /* create the array class */ + return class_array_of(comp, false); - /* initialize super class */ - if (c->super) { - if (initverbose) { - char logtext[MAXLOGTEXT]; - sprintf(logtext, "Initialize super class "); - utf_sprint(logtext + strlen(logtext), c->super->name); - sprintf(logtext + strlen(logtext), " from "); - utf_sprint(logtext + strlen(logtext), c->name); - log_text(logtext); + default: + /* primitive array classes are loaded by the bootstrap loader */ + return load_class_bootstrap(name); + } } - class_init(c->super); - } + + LOADER_ASSERT(class_java_lang_Object); + + lc = class_resolveclassmethod(cl->vftbl->class, + utf_loadClass, + utf_java_lang_String__java_lang_Class, + class_java_lang_Object, + true); + + if (!lc) + return false; /* exception */ + + LOADER_INC(); + r = (classinfo *) asm_calljavafunction(lc, + cl, + javastring_new_slash_to_dot(name), + NULL, NULL); + LOADER_DEC(); + + if (r) { + /* Store this class in the loaded class cache. If another + class with the same (initloader,name) pair has been + stored earlier it will be returned by classcache_store + In this case classcache_store may not free the class + because it has already been exposed to Java code which + may have kept references to that class. */ + + classinfo *c = classcache_store(cl,r,false); + + if (c == NULL) { + /* exception, free the loaded class */ + r->loaded = false; + class_free(r); + } - /* initialize interface classes */ - for (i = 0; i < c->interfacescount; i++) { - if (initverbose) { - char logtext[MAXLOGTEXT]; - sprintf(logtext, "Initialize interface class "); - utf_sprint(logtext + strlen(logtext), c->interfaces[i]->name); - sprintf(logtext + strlen(logtext), " from "); - utf_sprint(logtext + strlen(logtext), c->name); - log_text(logtext); + r = c; } - class_init(c->interfaces[i]); /* real */ - } - - m = class_findmethod(c, utf_clinit, utf_fidesc); - if (!m) { - if (initverbose) { - char logtext[MAXLOGTEXT]; - sprintf(logtext, "Class "); - utf_sprint(logtext + strlen(logtext), c->name); - sprintf(logtext + strlen(logtext), " has no initializer"); - log_text(logtext); + else { + /* loadClass has thrown an exception */ + /* we must convert ClassNotFoundException into NoClassDefFoundException */ + /* XXX maybe we should have a flag that avoids this conversion */ + /* for calling load_class_from_classloader from Class.forName */ + /* Currently we do a double conversion in these cases */ + classnotfoundexception_to_noclassdeffounderror(); } - /* goto callinitialize;*/ - return; - } - if (!(m->flags & ACC_STATIC)) - panic("Class initializer is not static!"); + /* SUN compatible -verbose:class output */ - if (initverbose) { - char logtext[MAXLOGTEXT]; - sprintf(logtext, "Starting initializer for class: "); - utf_sprint(logtext + strlen(logtext), c->name); - log_text(logtext); - } + if (opt_verboseclass && (r != NULL) && (r->classloader == cl)) { + printf("[Loaded "); + utf_display_classname(name); + printf("]\n"); + } -#if defined(USE_THREADS) && !defined(NATIVE_THREADS) - b = blockInts; - blockInts = 0; -#endif + return r; + } - /* now call the initializer */ - asm_calljavafunction(m, NULL, NULL, NULL, NULL); + LOADER_INC(); + r = load_class_bootstrap(name); + LOADER_DEC(); -#if defined(USE_THREADS) && !defined(NATIVE_THREADS) - assert(blockInts == 0); - blockInts = b; -#endif + return r; +} - /* we have to throw an exception */ - if (*exceptionptr) { - printf("Exception in thread \"main\" java.lang.ExceptionInInitializerError\n"); - printf("Caused by: "); - utf_display((*exceptionptr)->vftbl->class->name); - printf("\n"); - fflush(stdout); - exit(1); - } - if (initverbose) { - char logtext[MAXLOGTEXT]; - sprintf(logtext, "Finished initializer for class: "); - utf_sprint(logtext + strlen(logtext), c->name); - log_text(logtext); - } +/* load_class_bootstrap ******************************************************** + + Load the class with the given name using the bootstrap class loader. - if (c->name == utf_systemclass) { - /* class java.lang.System requires explicit initialization */ + IN: + name.............the classname - if (initverbose) - printf("#### Initializing class System"); + RETURN VALUE: + loaded classinfo, or + NULL if an exception has been thrown - /* find initializing method */ - m = class_findmethod(c, - utf_initsystemclass, - utf_fidesc); + SYNCHRONIZATION: + load_class_bootstrap is synchronized. It can be treated as an + atomic operation. - if (!m) { - /* no method found */ - /* printf("initializeSystemClass failed"); */ - return; - } +*******************************************************************************/ -#if defined(USE_THREADS) && !defined(NATIVE_THREADS) - b = blockInts; - blockInts = 0; +classinfo *load_class_bootstrap(utf *name) +{ + classbuffer *cb; + classinfo *c; + classinfo *r; +#ifdef LOADER_VERBOSE + char logtext[MAXLOGTEXT]; #endif - asm_calljavafunction(m, NULL, NULL, NULL, NULL); - -#if defined(USE_THREADS) && !defined(NATIVE_THREADS) - assert(blockInts == 0); - blockInts = b; -#endif + /* for debugging */ - if (*exceptionptr) { - printf("#### initializeSystemClass has thrown: "); - utf_display((*exceptionptr)->vftbl->class->name); - printf("\n"); - fflush(stdout); - } - } -} + LOADER_ASSERT(name); + LOADER_INC(); + /* lookup if this class has already been loaded */ -/********* Function: find_class_method_constant *********/ + if ((r = classcache_lookup(NULL, name))) + goto success; -int find_class_method_constant (classinfo *c, utf * c1, utf* m1, utf* d1) -{ - u4 i; - voidptr e; +#ifdef LOADER_VERBOSE + LOADER_INDENT(logtext); + strcat(logtext,"load_class_bootstrap("); + utf_sprint(logtext+strlen(logtext),name);strcat(logtext,")"); + log_text(logtext); +#endif - for (i=0; icpcount; i++) { - - e = c -> cpinfos [i]; - if (e) { - - switch (c -> cptags [i]) { - case CONSTANT_Methodref: - { - constant_FMIref *fmi = e; - if ( (fmi->class->name == c1) - && (fmi->name == m1) - && (fmi->descriptor == d1)) { - - return i; - } - } - break; + /* create the classinfo */ - case CONSTANT_InterfaceMethodref: - { - constant_FMIref *fmi = e; - if ( (fmi->class->name == c1) - && (fmi->name == m1) - && (fmi->descriptor == d1)) { + c = class_create_classinfo(name); + + /* handle array classes */ - return i; - } - } - break; - } - } + if (name->text[0] == '[') { + c = load_newly_created_array(c, NULL); + if (c == NULL) + goto return_exception; + LOADER_ASSERT(c->loaded); + r = c; + goto success; } - return -1; -} +#if defined(STATISTICS) + /* measure time */ + if (getcompilingtime) + compilingtime_stop(); -void class_showconstanti(classinfo *c, int ii) -{ - u4 i = ii; - voidptr e; - - e = c->cpinfos [i]; - printf ("#%d: ", (int) i); - if (e) { - switch (c->cptags [i]) { - case CONSTANT_Class: - printf("Classreference -> "); - utf_display(((classinfo*)e)->name); - break; - - case CONSTANT_Fieldref: - printf("Fieldref -> "); goto displayFMIi; - case CONSTANT_Methodref: - printf("Methodref -> "); goto displayFMIi; - case CONSTANT_InterfaceMethodref: - printf("InterfaceMethod -> "); goto displayFMIi; - displayFMIi: - { - constant_FMIref *fmi = e; - utf_display(fmi->class->name); - printf("."); - utf_display(fmi->name); - printf(" "); - utf_display(fmi->descriptor); - } - break; + if (getloadingtime) + loadingtime_start(); +#endif - case CONSTANT_String: - printf("String -> "); - utf_display(e); - break; - case CONSTANT_Integer: - printf("Integer -> %d", (int) (((constant_integer*)e)->value)); - break; - case CONSTANT_Float: - printf("Float -> %f", ((constant_float*)e)->value); - break; - case CONSTANT_Double: - printf("Double -> %f", ((constant_double*)e)->value); - break; - case CONSTANT_Long: - { - u8 v = ((constant_long*)e)->value; -#if U8_AVAILABLE - printf("Long -> %ld", (long int) v); -#else - printf("Long -> HI: %ld, LO: %ld\n", - (long int) v.high, (long int) v.low); -#endif - } - break; - case CONSTANT_NameAndType: - { - constant_nameandtype *cnt = e; - printf("NameAndType: "); - utf_display(cnt->name); - printf(" "); - utf_display(cnt->descriptor); - } - break; - case CONSTANT_Utf8: - printf("Utf8 -> "); - utf_display(e); - break; - default: - panic("Invalid type of ConstantPool-Entry"); - } + /* load classdata, throw exception on error */ + + if ((cb = suck_start(c)) == NULL) { + /* this normally means, the classpath was not set properly */ + + if (name == utf_java_lang_Object) + throw_cacao_exception_exit(string_java_lang_NoClassDefFoundError, + "java/lang/Object"); + + *exceptionptr = + new_exception_utfmessage(string_java_lang_NoClassDefFoundError, + name); + goto return_exception; } - printf("\n"); -} + + /* load the class from the buffer */ + r = load_class_from_classbuffer(cb); -void class_showconstantpool (classinfo *c) -{ - u4 i; - voidptr e; + if (!r) { + /* the class could not be loaded, free the classinfo struct */ - printf ("---- dump of constant pool ----\n"); + class_free(c); - for (i=0; icpcount; i++) { - printf ("#%d: ", (int) i); - - e = c -> cpinfos [i]; - if (e) { - - switch (c -> cptags [i]) { - case CONSTANT_Class: - printf ("Classreference -> "); - utf_display ( ((classinfo*)e) -> name ); - break; - - case CONSTANT_Fieldref: - printf ("Fieldref -> "); goto displayFMI; - case CONSTANT_Methodref: - printf ("Methodref -> "); goto displayFMI; - case CONSTANT_InterfaceMethodref: - printf ("InterfaceMethod -> "); goto displayFMI; - displayFMI: - { - constant_FMIref *fmi = e; - utf_display ( fmi->class->name ); - printf ("."); - utf_display ( fmi->name); - printf (" "); - utf_display ( fmi->descriptor ); - } - break; + } else { + /* Store this class in the loaded class cache this step also + checks the loading constraints. If the class has been loaded + before, the earlier loaded class is returned. */ - case CONSTANT_String: - printf ("String -> "); - utf_display (e); - break; - case CONSTANT_Integer: - printf ("Integer -> %d", (int) ( ((constant_integer*)e) -> value) ); - break; - case CONSTANT_Float: - printf ("Float -> %f", ((constant_float*)e) -> value); - break; - case CONSTANT_Double: - printf ("Double -> %f", ((constant_double*)e) -> value); - break; - case CONSTANT_Long: - { - u8 v = ((constant_long*)e) -> value; -#if U8_AVAILABLE - printf ("Long -> %ld", (long int) v); -#else - printf ("Long -> HI: %ld, LO: %ld\n", - (long int) v.high, (long int) v.low); -#endif - } - break; - case CONSTANT_NameAndType: - { - constant_nameandtype *cnt = e; - printf ("NameAndType: "); - utf_display (cnt->name); - printf (" "); - utf_display (cnt->descriptor); - } - break; - case CONSTANT_Utf8: - printf ("Utf8 -> "); - utf_display (e); - break; - default: - panic ("Invalid type of ConstantPool-Entry"); - } + classinfo *res = classcache_store(NULL, c, true); + + if (!res) { + /* exception */ + class_free(c); } - printf ("\n"); + r = res; } -} + /* SUN compatible -verbose:class output */ + if (opt_verboseclass && r) { + printf("[Loaded "); + utf_display_classname(name); + printf(" from %s]\n", cb->path); + } -/********** Function: class_showmethods (debugging only) *************/ - -void class_showmethods (classinfo *c) -{ - s4 i; - - printf ("--------- Fields and Methods ----------------\n"); - printf ("Flags: "); printflags (c->flags); printf ("\n"); + /* free memory */ - printf ("This: "); utf_display (c->name); printf ("\n"); - if (c->super) { - printf ("Super: "); utf_display (c->super->name); printf ("\n"); - } - printf ("Index: %d\n", c->index); - - printf ("interfaces:\n"); - for (i=0; i < c-> interfacescount; i++) { - printf (" "); - utf_display (c -> interfaces[i] -> name); - printf (" (%d)\n", c->interfaces[i] -> index); - } + suck_stop(cb); - printf ("fields:\n"); - for (i=0; i < c -> fieldscount; i++) { - field_display (&(c -> fields[i])); - } +#if defined(STATISTICS) + /* measure time */ - printf ("methods:\n"); - for (i=0; i < c -> methodscount; i++) { - methodinfo *m = &(c->methods[i]); - if ( !(m->flags & ACC_STATIC)) - printf ("vftblindex: %d ", m->vftblindex); + if (getloadingtime) + loadingtime_stop(); - method_display ( m ); + if (getcompilingtime) + compilingtime_start(); +#endif - } + if (!r) + goto return_exception; - printf ("Virtual function table:\n"); - for (i=0; ivftbl->vftbllength; i++) { - printf ("entry: %d, %ld\n", i, (long int) (c->vftbl->table[i]) ); - } +success: + LOADER_DEC(); -} + return r; +return_exception: + LOADER_DEC(); + return NULL; +} -/******************************************************************************/ -/******************* General functions for the class loader *******************/ -/******************************************************************************/ -/********************* Function: loader_load *********************************** +/* load_class_from_classbuffer ************************************************* + + Loads everything interesting about a class from the class file. The + 'classinfo' structure must have been allocated previously. - Loads and links the class desired class and each class and interface - referenced by it. - Returns: a pointer to this class + The super class and the interfaces implemented by this class need + not be loaded. The link is set later by the function 'class_link'. + The loaded class is removed from the list 'unloadedclasses' and + added to the list 'unlinkedclasses'. + + SYNCHRONIZATION: + This function is NOT synchronized! + *******************************************************************************/ -static int loader_load_running = 0; - -classinfo *loader_load(utf *topname) +classinfo *load_class_from_classbuffer(classbuffer *cb) { - classinfo *top; classinfo *c; - s8 starttime = 0; - s8 stoptime = 0; - classinfo *notlinkable; - -#if defined(USE_THREADS) && defined(NATIVE_THREADS) - pthread_mutex_lock(&compiler_mutex); + utf *name; + utf *supername; + u4 i,j; + u4 ma, mi; + s4 dumpsize; + descriptor_pool *descpool; +#if defined(STATISTICS) + u4 classrefsize; + u4 descsize; +#endif +#ifdef LOADER_VERBOSE + char logtext[MAXLOGTEXT]; #endif - /* avoid recursive calls */ - if (loader_load_running) - return class_new(topname); + /* get the classbuffer's class */ - loader_load_running++; - -#if defined(USE_THREADS) && !defined(NATIVE_THREADS) - intsDisable(); + c = cb->class; + + /* maybe the class is already loaded */ + + if (c->loaded) + return c; + +#ifdef LOADER_VERBOSE + LOADER_INDENT(logtext); + strcat(logtext,"load_class_from_classbuffer("); + utf_sprint(logtext+strlen(logtext),c->name);strcat(logtext,")"); + log_text(logtext); + LOADER_INC(); #endif - if (getloadingtime) - starttime = getcputime(); +#if defined(STATISTICS) + if (opt_stat) + count_class_loads++; +#endif - top = class_new(topname); + /* output for debugging purposes */ - /* load classes */ - while ((c = list_first(&unloadedclasses))) { - if (!class_load(c)) { - if (linkverbose) - dolog("Failed to load class"); - list_remove(&unloadedclasses, c); - top = NULL; - } - } + if (loadverbose) + log_message_class("Loading class: ", c); + + /* mark start of dump memory area */ - /* link classes */ - if (linkverbose) - dolog("Linking..."); - - /* Added a hack to break infinite linking loops. A better - * linking algorithm would be nice. -Edwin */ - notlinkable = NULL; - while ((c = list_first(&unlinkedclasses))) { - class_link(c); - if (!c->linked) { - if (!notlinkable) - notlinkable = c; - else if (notlinkable == c) { - /* We tried to link this class for the second time and - * no other classes were linked in between, so we are - * caught in a loop. - */ - if (linkverbose) - dolog("Cannot resolve linking dependencies"); - top = NULL; - if (!*exceptionptr) - throw_linkageerror_message(c->name); - break; - } + dumpsize = dump_size(); - } else - notlinkable = NULL; - } - if (linkverbose) - dolog("Linking done."); + /* class is somewhat loaded */ - if (loader_inited) - loader_compute_subclasses(); + c->loaded = true; - /* measure time */ - if (getloadingtime) { - stoptime = getcputime(); - loadingtime += (stoptime - starttime); - } + if (!check_classbuffer_size(cb, 4 + 2 + 2)) + goto return_exception; + /* check signature */ - loader_load_running--; - - /* check if a former loader_load call tried to load/link the class and - failed. This is needed because the class didn't appear in the - undloadclasses or unlinkedclasses list during this class. */ - if (top) { - if (!top->loaded) { - if (linkverbose) dolog("Failed to load class (former call)"); - throw_noclassdeffounderror_message(top->name); - top = NULL; - - } else if (!top->linked) { - if (linkverbose) - dolog("Failed to link class (former call)"); - throw_linkageerror_message(top->name); - top = NULL; - } - } + if (suck_u4(cb) != MAGIC) { + *exceptionptr = new_classformaterror(c, "Bad magic number"); -#if defined(USE_THREADS) && !defined(NATIVE_THREADS) - intsRestore(); -#endif - -#if defined(USE_THREADS) && defined(NATIVE_THREADS) - pthread_mutex_unlock(&compiler_mutex); -#endif + goto return_exception; + } - /* DEBUG */ /*if (linkverbose && !top) dolog("returning NULL from loader_load");*/ - - return top; -} + /* check version */ + mi = suck_u2(cb); + ma = suck_u2(cb); -/****************** Function: loader_load_sysclass **************************** + if (!(ma < MAJOR_VERSION || (ma == MAJOR_VERSION && mi <= MINOR_VERSION))) { + *exceptionptr = + new_unsupportedclassversionerror(c, + "Unsupported major.minor version %d.%d", + ma, mi); - Loads and links the class desired class and each class and interface - referenced by it. + goto return_exception; + } - The pointer to the classinfo is stored in *top if top != NULL. - The pointer is also returned. + /* create a new descriptor pool */ - If the class could not be loaded the function aborts with an error. + descpool = descriptor_pool_new(c); -*******************************************************************************/ + /* load the constant pool */ -classinfo *loader_load_sysclass(classinfo **top, utf *topname) -{ - classinfo *cls; + if (!load_constantpool(cb, descpool)) + goto return_exception; - if ((cls = loader_load(topname)) == NULL) { - log_plain("Could not load important system class: "); - log_plain_utf(topname); - log_nl(); - panic("Could not load important system class"); - } + /*JOWENN*/ + c->erroneous_state = 0; + c->initializing_thread = 0; + /*JOWENN*/ + c->classUsed = NOTUSED; /* not used initially CO-RT */ + c->impldBy = NULL; - if (top) *top = cls; + /* ACC flags */ - return cls; -} + if (!check_classbuffer_size(cb, 2)) + goto return_exception; + c->flags = suck_u2(cb); -/**************** function: create_primitive_classes *************************** + /* check ACC flags consistency */ - create classes representing primitive types + if (c->flags & ACC_INTERFACE) { + if (!(c->flags & ACC_ABSTRACT)) { + /* We work around this because interfaces in JDK 1.1 are + * not declared abstract. */ -********************************************************************************/ + c->flags |= ACC_ABSTRACT; + } + if (c->flags & ACC_FINAL) { + *exceptionptr = + new_classformaterror(c, + "Illegal class modifiers: 0x%X", c->flags); -void create_primitive_classes() -{ - int i; + goto return_exception; + } - for (i=0;i classUsed = NOTUSED; /* not used initially CO-RT */ - c -> impldBy = NULL; - - /* prevent loader from loading primitive class */ - list_remove (&unloadedclasses, c); - c->loaded=true; - /* add to unlinked classes */ - list_addlast (&unlinkedclasses, c); -/*JOWENN primitive types don't have objects as super class c -> super = class_java_lang_Object; */ - class_link (c); - - primitivetype_table[i].class_primitive = c; - - /* create class for wrapping the primitive type */ - primitivetype_table[i].class_wrap = - class_new( utf_new_char(primitivetype_table[i].wrapname) ); - primitivetype_table[i].class_wrap -> classUsed = NOTUSED; /* not used initially CO-RT */ - primitivetype_table[i].class_wrap -> impldBy = NULL; - - /* create the primitive array class */ - if (primitivetype_table[i].arrayname) { - c = class_new( utf_new_char(primitivetype_table[i].arrayname) ); - primitivetype_table[i].arrayclass = c; - c->loaded=true; - if (!c->linked) class_link(c); - primitivetype_table[i].arrayvftbl = c->vftbl; + if (c->flags & ACC_SUPER) { + c->flags &= ~ACC_SUPER; /* kjc seems to set this on interfaces */ } } -} -/**************** function: class_primitive_from_sig *************************** + if ((c->flags & (ACC_ABSTRACT | ACC_FINAL)) == (ACC_ABSTRACT | ACC_FINAL)) { + *exceptionptr = + new_classformaterror(c, "Illegal class modifiers: 0x%X", c->flags); - return the primitive class indicated by the given signature character + goto return_exception; + } - If the descriptor does not indicate a valid primitive type the - return value is NULL. + if (!check_classbuffer_size(cb, 2 + 2)) + goto return_exception; -********************************************************************************/ + /* this class */ -classinfo *class_primitive_from_sig(char sig) -{ - switch (sig) { - case 'I': return primitivetype_table[PRIMITIVETYPE_INT].class_primitive; - case 'J': return primitivetype_table[PRIMITIVETYPE_LONG].class_primitive; - case 'F': return primitivetype_table[PRIMITIVETYPE_FLOAT].class_primitive; - case 'D': return primitivetype_table[PRIMITIVETYPE_DOUBLE].class_primitive; - case 'B': return primitivetype_table[PRIMITIVETYPE_BYTE].class_primitive; - case 'C': return primitivetype_table[PRIMITIVETYPE_CHAR].class_primitive; - case 'S': return primitivetype_table[PRIMITIVETYPE_SHORT].class_primitive; - case 'Z': return primitivetype_table[PRIMITIVETYPE_BOOLEAN].class_primitive; - case 'V': return primitivetype_table[PRIMITIVETYPE_VOID].class_primitive; - } - return NULL; -} + i = suck_u2(cb); + if (!(name = (utf *) class_getconstant(c, i, CONSTANT_Class))) + goto return_exception; -/****************** function: class_from_descriptor **************************** + if (c->name == utf_not_named_yet) { + /* we finally have a name for this class */ + c->name = name; + class_set_packagename(c); - return the class indicated by the given descriptor + } else if (name != c->name) { + char *msg; + s4 msglen; - utf_ptr....first character of descriptor - end_ptr....first character after the end of the string - next.......if non-NULL, *next is set to the first character after - the descriptor. (Undefined if an error occurs.) + msglen = utf_strlen(c->name) + strlen(" (wrong name: ") + + utf_strlen(name) + strlen(")") + strlen("0"); - mode.......a combination (binary or) of the following flags: + msg = MNEW(char, msglen); - (Flags marked with * are the default settings.) + utf_sprint(msg, c->name); + strcat(msg, " (wrong name: "); + utf_strcat(msg, name); + strcat(msg, ")"); - What to do if a reference type descriptor is parsed successfully: + *exceptionptr = + new_exception_message(string_java_lang_NoClassDefFoundError, msg); - CLASSLOAD_SKIP...skip it and return something != NULL - * CLASSLOAD_NEW....get classinfo * via class_new - CLASSLOAD_LOAD...get classinfo * via loader_load + MFREE(msg, char, msglen); - How to handle primitive types: + goto return_exception; + } + + /* retrieve superclass */ - * CLASSLOAD_PRIMITIVE.......return primitive class (eg. "int") - CLASSLOAD_NULLPRIMITIVE...return NULL for primitive types + c->super.any = NULL; + if ((i = suck_u2(cb))) { + if (!(supername = (utf *) class_getconstant(c, i, CONSTANT_Class))) + goto return_exception; - How to handle "V" descriptors: + /* java.lang.Object may not have a super class. */ - * CLASSLOAD_VOID.....handle it like other primitive types - CLASSLOAD_NOVOID...treat it as an error + if (c->name == utf_java_lang_Object) { + *exceptionptr = + new_exception_message(string_java_lang_ClassFormatError, + "java.lang.Object with superclass"); - How to deal with extra characters after the end of the - descriptor: + goto return_exception; + } - * CLASSLOAD_NOCHECKEND...ignore (useful for parameter lists) - CLASSLOAD_CHECKEND.....treat them as an error + /* Interfaces must have java.lang.Object as super class. */ - How to deal with errors: + if ((c->flags & ACC_INTERFACE) && + supername != utf_java_lang_Object) { + *exceptionptr = + new_exception_message(string_java_lang_ClassFormatError, + "Interfaces must have java.lang.Object as superclass"); - * CLASSLOAD_PANIC....abort execution with an error message - CLASSLOAD_NOPANIC..return NULL on error + goto return_exception; + } -********************************************************************************/ + } else { + supername = NULL; -classinfo *class_from_descriptor(char *utf_ptr, char *end_ptr, - char **next, int mode) -{ - char *start = utf_ptr; - bool error = false; - utf *name; + /* This is only allowed for java.lang.Object. */ - SKIP_FIELDDESCRIPTOR_SAFE(utf_ptr,end_ptr,error); + if (c->name != utf_java_lang_Object) { + *exceptionptr = new_classformaterror(c, "Bad superclass index"); - if (mode & CLASSLOAD_CHECKEND) - error |= (utf_ptr != end_ptr); - - if (!error) { - if (next) *next = utf_ptr; - - switch (*start) { - case 'V': - if (mode & CLASSLOAD_NOVOID) - break; - /* FALLTHROUGH! */ - case 'I': - case 'J': - case 'F': - case 'D': - case 'B': - case 'C': - case 'S': - case 'Z': - return (mode & CLASSLOAD_NULLPRIMITIVE) - ? NULL - : class_primitive_from_sig(*start); - - case 'L': - start++; - utf_ptr--; - /* FALLTHROUGH! */ - case '[': - if (mode & CLASSLOAD_SKIP) return class_java_lang_Object; - name = utf_new(start,utf_ptr-start); - return (mode & CLASSLOAD_LOAD) - ? loader_load(name) : class_new(name); /* XXX handle errors */ + goto return_exception; } } + + /* retrieve interfaces */ - /* An error occurred */ - if (mode & CLASSLOAD_NOPANIC) - return NULL; + if (!check_classbuffer_size(cb, 2)) + goto return_exception; - log_plain("Invalid descriptor at beginning of '"); - log_plain_utf(utf_new(start, end_ptr-start)); - log_plain("'"); - log_nl(); - - panic("Invalid descriptor"); + c->interfacescount = suck_u2(cb); - /* keep compiler happy */ - return NULL; -} + if (!check_classbuffer_size(cb, 2 * c->interfacescount)) + goto return_exception; + c->interfaces = MNEW(classref_or_classinfo, c->interfacescount); + for (i = 0; i < c->interfacescount; i++) { + /* the classrefs are created later */ + if (!(c->interfaces[i].any = (utf *) class_getconstant(c, suck_u2(cb), CONSTANT_Class))) + goto return_exception; + } -/******************* function: type_from_descriptor **************************** + /* load fields */ + if (!check_classbuffer_size(cb, 2)) + goto return_exception; - return the basic type indicated by the given descriptor + c->fieldscount = suck_u2(cb); + c->fields = GCNEW_UNCOLLECTABLE(fieldinfo, c->fieldscount); +/* c->fields = MNEW(fieldinfo, c->fieldscount); */ + for (i = 0; i < c->fieldscount; i++) { + if (!load_field(cb, &(c->fields[i]),descpool)) + goto return_exception; + } - This function parses a descriptor and returns its basic type as - TYPE_INT, TYPE_LONG, TYPE_FLOAT, TYPE_DOUBLE, TYPE_ADDRESS or TYPE_VOID. + /* load methods */ + if (!check_classbuffer_size(cb, 2)) + goto return_exception; - cls...if non-NULL the referenced variable is set to the classinfo * - returned by class_from_descriptor. + c->methodscount = suck_u2(cb); +/* c->methods = GCNEW(methodinfo, c->methodscount); */ + c->methods = MNEW(methodinfo, c->methodscount); + for (i = 0; i < c->methodscount; i++) { + if (!load_method(cb, &(c->methods[i]),descpool)) + goto return_exception; + } - For documentation of the arguments utf_ptr, end_ptr, next and mode - see class_from_descriptor. The only difference is that - type_from_descriptor always uses CLASSLOAD_PANIC. + /* create the class reference table */ -********************************************************************************/ + c->classrefs = + descriptor_pool_create_classrefs(descpool, &(c->classrefcount)); -int type_from_descriptor(classinfo **cls, char *utf_ptr, char *end_ptr, - char **next, int mode) -{ - classinfo *mycls; - if (!cls) cls = &mycls; - *cls = class_from_descriptor(utf_ptr, end_ptr, next, mode & (~CLASSLOAD_NOPANIC)); - switch (*utf_ptr) { - case 'B': - case 'C': - case 'I': - case 'S': - case 'Z': - return TYPE_INT; - case 'D': - return TYPE_DOUBLE; - case 'F': - return TYPE_FLOAT; - case 'J': - return TYPE_LONG; - case 'V': - return TYPE_VOID; - } - return TYPE_ADDRESS; -} + /* allocate space for the parsed descriptors */ + descriptor_pool_alloc_parsed_descriptors(descpool); + c->parseddescs = + descriptor_pool_get_parsed_descriptors(descpool, &(c->parseddescsize)); +#if defined(STATISTICS) + if (opt_stat) { + descriptor_pool_get_sizes(descpool, &classrefsize, &descsize); + count_classref_len += classrefsize; + count_parsed_desc_len += descsize; + } +#endif -/*************** function: create_system_exception_classes ******************************* + /* put the classrefs in the constant pool */ + for (i = 0; i < c->cpcount; i++) { + if (c->cptags[i] == CONSTANT_Class) { + utf *name = (utf *) c->cpinfos[i]; + c->cpinfos[i] = descriptor_pool_lookup_classref(descpool, name); + } + } - create system exception classes needed by default + /* set the super class reference */ -********************************************************************************/ + if (supername) { + c->super.ref = descriptor_pool_lookup_classref(descpool, supername); + if (!c->super.ref) + goto return_exception; + } -static void create_system_exception_classes() -{ + /* set the super interfaces references */ - if (verbose) log_text("loader_init: create_system_exception_classs: loader_load: java/lang/ClassCastException"); - loader_load_sysclass(&class_java_lang_ClassCastException, - utf_new_char ("java/lang/ClassCastException")); - loader_load_sysclass(&class_java_lang_NullPointerException, - utf_new_char ("java/lang/NullPointerException")); - loader_load_sysclass(&class_java_lang_ArrayIndexOutOfBoundsException, - utf_new_char ("java/lang/ArrayIndexOutOfBoundsException")); - loader_load_sysclass(&class_java_lang_NegativeArraySizeException, - utf_new_char ("java/lang/NegativeArraySizeException")); - loader_load_sysclass(&class_java_lang_OutOfMemoryError, - utf_new_char ("java/lang/OutOfMemoryError")); - loader_load_sysclass(&class_java_lang_ArrayStoreException, - utf_new_char ("java/lang/ArrayStoreException")); - loader_load_sysclass(&class_java_lang_ArithmeticException, - utf_new_char ("java/lang/ArithmeticException")); - loader_load_sysclass(&class_java_lang_ThreadDeath, - utf_new_char ("java/lang/ThreadDeath")); + for (i = 0; i < c->interfacescount; i++) { + c->interfaces[i].ref = + descriptor_pool_lookup_classref(descpool, + (utf *) c->interfaces[i].any); + if (!c->interfaces[i].ref) + goto return_exception; + } + /* parse field descriptors */ -} + for (i = 0; i < c->fieldscount; i++) { + c->fields[i].parseddesc = + descriptor_pool_parse_field_descriptor(descpool, + c->fields[i].descriptor); + if (!c->fields[i].parseddesc) + goto return_exception; + } + /* parse method descriptors */ -/*************** function: create_system_exception_classes ******************************* + for (i = 0; i < c->methodscount; i++) { + methodinfo *m = &c->methods[i]; + m->parseddesc = + descriptor_pool_parse_method_descriptor(descpool, m->descriptor, + m->flags, class_get_self_classref(m->class)); + if (!m->parseddesc) + goto return_exception; + + for (j = 0; j < m->exceptiontablelength; j++) { + if (!m->exceptiontable[j].catchtype.any) + continue; + if ((m->exceptiontable[j].catchtype.ref = + descriptor_pool_lookup_classref(descpool, + (utf *) m->exceptiontable[j].catchtype.any)) == NULL) + goto return_exception; + } - create system exception proto classes needed by default + for (j = 0; j < m->thrownexceptionscount; j++) { + if (!m->thrownexceptions[j].any) + continue; + if ((m->thrownexceptions[j].ref = descriptor_pool_lookup_classref(descpool, + (utf *) m->thrownexceptions[j].any)) == NULL) + goto return_exception; + } + } -********************************************************************************/ + /* parse the loaded descriptors */ -static void create_system_exception_proto_classes() -{ + for (i = 0; i < c->cpcount; i++) { + constant_FMIref *fmi; + s4 index; + + switch (c->cptags[i]) { + case CONSTANT_Fieldref: + fmi = (constant_FMIref *) c->cpinfos[i]; + fmi->parseddesc.fd = + descriptor_pool_parse_field_descriptor(descpool, + fmi->descriptor); + if (!fmi->parseddesc.fd) + goto return_exception; + index = (int) (size_t) fmi->classref; + fmi->classref = + (constant_classref *) class_getconstant(c, index, + CONSTANT_Class); + if (!fmi->classref) + goto return_exception; + break; + case CONSTANT_Methodref: + case CONSTANT_InterfaceMethodref: + fmi = (constant_FMIref *) c->cpinfos[i]; + index = (int) (size_t) fmi->classref; + fmi->classref = + (constant_classref *) class_getconstant(c, index, + CONSTANT_Class); + if (!fmi->classref) + goto return_exception; + fmi->parseddesc.md = + descriptor_pool_parse_method_descriptor(descpool, + fmi->descriptor, + ACC_UNDEF, + fmi->classref); + if (!fmi->parseddesc.md) + goto return_exception; + break; + } + } - if (verbose) log_text("loader_init: creating global proto_java_lang_ClassCastException"); - proto_java_lang_ClassCastException = - builtin_new(class_java_lang_ClassCastException); + /* Check if all fields and methods can be uniquely + * identified by (name,descriptor). */ - if (verbose) log_text("loader_init: proto_java_lang_ClassCastException has been initialized"); + if (opt_verify) { + /* We use a hash table here to avoid making the + * average case quadratic in # of methods, fields. + */ + static int shift = 0; + u2 *hashtab; + u2 *next; /* for chaining colliding hash entries */ + size_t len; + size_t hashlen; + u2 index; + u2 old; - proto_java_lang_NullPointerException = - builtin_new(class_java_lang_NullPointerException); - if (verbose) log_text("loader_init: proto_java_lang_NullPointerException has been initialized"); + /* Allocate hashtable */ + len = c->methodscount; + if (len < c->fieldscount) len = c->fieldscount; + hashlen = 5 * len; + hashtab = MNEW(u2,(hashlen + len)); + next = hashtab + hashlen; - proto_java_lang_ArrayIndexOutOfBoundsException = - builtin_new(class_java_lang_ArrayIndexOutOfBoundsException); + /* Determine bitshift (to get good hash values) */ + if (!shift) { + len = sizeof(utf); + while (len) { + len >>= 1; + shift++; + } + } - proto_java_lang_NegativeArraySizeException = - builtin_new(class_java_lang_NegativeArraySizeException); + /* Check fields */ + memset(hashtab, 0, sizeof(u2) * (hashlen + len)); - proto_java_lang_OutOfMemoryError = - builtin_new(class_java_lang_OutOfMemoryError); + for (i = 0; i < c->fieldscount; ++i) { + fieldinfo *fi = c->fields + i; - proto_java_lang_ArithmeticException = - builtin_new(class_java_lang_ArithmeticException); + /* It's ok if we lose bits here */ + index = ((((size_t) fi->name) + + ((size_t) fi->descriptor)) >> shift) % hashlen; - proto_java_lang_ArrayStoreException = - builtin_new(class_java_lang_ArrayStoreException); + if ((old = hashtab[index])) { + old--; + next[i] = old; + do { + if (c->fields[old].name == fi->name && + c->fields[old].descriptor == fi->descriptor) { + *exceptionptr = + new_classformaterror(c, + "Repetitive field name/signature"); - proto_java_lang_ThreadDeath = - builtin_new(class_java_lang_ThreadDeath); + goto return_exception; + } + } while ((old = next[old])); + } + hashtab[index] = i + 1; + } + + /* Check methods */ + memset(hashtab, 0, sizeof(u2) * (hashlen + hashlen/5)); + for (i = 0; i < c->methodscount; ++i) { + methodinfo *mi = c->methods + i; -} + /* It's ok if we lose bits here */ + index = ((((size_t) mi->name) + + ((size_t) mi->descriptor)) >> shift) % hashlen; + /*{ JOWENN + int dbg; + for (dbg=0;dbgmethods[old].name == mi->name && + c->methods[old].descriptor == mi->descriptor) { + *exceptionptr = + new_classformaterror(c, + "Repetitive method name/signature"); -/*************** function: create_pseudo_classes ******************************* + goto return_exception; + } + } while ((old = next[old])); + } + hashtab[index] = i + 1; + } + + MFREE(hashtab, u2, (hashlen + len)); + } - create pseudo classes used by the typechecker +#if defined(STATISTICS) + if (opt_stat) { + count_class_infos += sizeof(classinfo*) * c->interfacescount; + count_class_infos += sizeof(fieldinfo) * c->fieldscount; + count_class_infos += sizeof(methodinfo) * c->methodscount; + } +#endif -********************************************************************************/ + /* load attribute structures */ -static void create_pseudo_classes() -{ - /* pseudo class for Arraystubs (extends java.lang.Object) */ - - pseudo_class_Arraystub = class_new(utf_new_char("$ARRAYSTUB$")); - list_remove(&unloadedclasses, pseudo_class_Arraystub); + if (!check_classbuffer_size(cb, 2)) + goto return_exception; - pseudo_class_Arraystub->super = class_java_lang_Object; - pseudo_class_Arraystub->interfacescount = 2; - pseudo_class_Arraystub->interfaces = MNEW(classinfo*, 2); - pseudo_class_Arraystub->interfaces[0] = class_java_lang_Cloneable; - pseudo_class_Arraystub->interfaces[1] = class_java_io_Serializable; + if (!load_attributes(cb, suck_u2(cb))) + goto return_exception; - list_addlast(&unlinkedclasses, pseudo_class_Arraystub); - class_link(pseudo_class_Arraystub); +#if 0 + /* Pre java 1.5 version don't check this. This implementation is like + java 1.5 do it: for class file version 45.3 we don't check it, older + versions are checked. + */ + if ((ma == 45 && mi > 3) || ma > 45) { + /* check if all data has been read */ + s4 classdata_left = ((cb->data + cb->size) - cb->pos - 1); + + if (classdata_left > 0) { + *exceptionptr = + new_classformaterror(c, "Extra bytes at the end of class file"); + goto return_exception; + } + } +#endif - pseudo_class_Arraystub_vftbl = pseudo_class_Arraystub->vftbl; + /* release dump area */ - /* pseudo class representing the null type */ - - pseudo_class_Null = class_new(utf_new_char("$NULL$")); - list_remove(&unloadedclasses, pseudo_class_Null); + dump_release(dumpsize); + + if (loadverbose) + log_message_class("Loading done class: ", c); - pseudo_class_Null->super = class_java_lang_Object; + LOADER_DEC(); + return c; - list_addlast(&unlinkedclasses, pseudo_class_Null); - class_link(pseudo_class_Null); +return_exception: + /* release dump area */ - /* pseudo class representing new uninitialized objects */ - - pseudo_class_New = class_new(utf_new_char("$NEW$")); - list_remove(&unloadedclasses, pseudo_class_New); + dump_release(dumpsize); - pseudo_class_New->super = class_java_lang_Object; + /* an exception has been thrown */ - list_addlast(&unlinkedclasses, pseudo_class_New); - class_link(pseudo_class_New); + LOADER_DEC(); + return NULL; } -/********************** Function: loader_init ********************************** +/* load_newly_created_array **************************************************** - Initializes all lists and loads all classes required for the system or the - compiler. + Load a newly created array class. -*******************************************************************************/ - -void loader_init(u1 *stackbottom) -{ - interfaceindex = 0; - - list_init(&unloadedclasses, OFFSET(classinfo, listnode)); - list_init(&unlinkedclasses, OFFSET(classinfo, listnode)); - list_init(&linkedclasses, OFFSET(classinfo, listnode)); - - /* create utf-symbols for pointer comparison of frequently used strings */ - utf_innerclasses = utf_new_char("InnerClasses"); - utf_constantvalue = utf_new_char("ConstantValue"); - utf_code = utf_new_char("Code"); - utf_exceptions = utf_new_char("Exceptions"); - utf_linenumbertable = utf_new_char("LineNumberTable"); - utf_finalize = utf_new_char("finalize"); - utf_fidesc = utf_new_char("()V"); - utf_init = utf_new_char(""); - utf_clinit = utf_new_char(""); - utf_initsystemclass = utf_new_char("initializeSystemClass"); - utf_systemclass = utf_new_char("java/lang/System"); - utf_vmclassloader = utf_new_char("java/lang/VMClassLoader"); - utf_initialize = utf_new_char("initialize"); - utf_initializedesc = utf_new_char("(I)V"); - - utf_vmclass = utf_new_char("java/lang/VMClass"); - utf_java_lang_Object= utf_new_char("java/lang/Object"); - - array_packagename = utf_new_char(""); - - /* create some important classes */ - /* These classes have to be created now because the classinfo - * pointers are used in the loading code. - */ - class_java_lang_Object = class_new(utf_new_char("java/lang/Object")); - class_java_lang_String = class_new(utf_new_char("java/lang/String")); - class_java_lang_Cloneable = class_new(utf_new_char("java/lang/Cloneable")); - class_java_io_Serializable = class_new(utf_new_char("java/io/Serializable")); + RETURN VALUE: + c....................the array class C has been loaded + other classinfo......the array class was found in the class cache, + C has been freed + NULL.................an exception has been thrown - if (verbose) log_text("loader_init: java/lang/Object"); - /* load the classes which were created above */ - loader_load_sysclass(NULL, class_java_lang_Object->name); + Note: + This is an internal function. Do not use it unless you know exactly + what you are doing! - loader_inited = 1; /*JOWENN*/ + Use one of the load_class_... functions for general array class loading. - loader_load_sysclass(&class_java_lang_Throwable, - utf_new_char("java/lang/Throwable")); +*******************************************************************************/ - create_system_exception_classes(); +classinfo *load_newly_created_array(classinfo *c, java_objectheader *loader) +{ + classinfo *comp = NULL; + methodinfo *clone; + methoddesc *clonedesc; + constant_classref *classrefs; + char *text; + s4 namelen; + utf *u; + +#ifdef LOADER_VERBOSE + char logtext[MAXLOGTEXT]; + LOADER_INDENT(logtext); + strcat(logtext,"load_newly_created_array(");utf_sprint_classname(logtext+strlen(logtext),c->name); + sprintf(logtext+strlen(logtext),") loader=%p",loader); + log_text(logtext); +#endif - /* create classes representing primitive types */ - create_primitive_classes(); + text = c->name->text; + namelen = c->name->blength; - /* create classes used by the typechecker */ - create_pseudo_classes(); + /* Check array class name */ - /* correct vftbl-entries (retarded loading of class java/lang/String) */ - stringtable_update(); + if (namelen < 2 || text[0] != '[') { + *exceptionptr = new_noclassdeffounderror(c->name); + return NULL; + } -#if defined(USE_THREADS) && !defined(NATIVE_THREADS) - if (stackbottom!=0) - initLocks(); -#endif - create_system_exception_proto_classes(); + /* Check the element type */ - loader_inited = 1; -} + switch (text[1]) { + case '[': + /* c is an array of arrays. We have to create the component class. */ + u = utf_new(text + 1, namelen - 1); + LOADER_INC(); + if (!(comp = load_class_from_classloader(u, loader))) { + LOADER_DEC(); + return NULL; + } + LOADER_DEC(); + LOADER_ASSERT(comp->loaded); + if (opt_eager) + if (!link_class(c)) + return NULL; + + /* the array's flags are that of the component class */ + c->flags = (comp->flags & ~ACC_INTERFACE) | ACC_FINAL | ACC_ABSTRACT; + c->classloader = comp->classloader; + break; + + case 'L': + /* c is an array of objects. */ + + /* check for cases like `[L;' or `[L[I;' or `[Ljava.lang.Object' */ + if (namelen < 4 || text[2] == '[' || text[namelen - 1] != ';') { + *exceptionptr = new_noclassdeffounderror(c->name); + return NULL; + } -/********************* Function: loader_initclasses **************************** + u = utf_new(text + 2, namelen - 3); - Initializes all loaded but uninitialized classes + LOADER_INC(); + if (!(comp = load_class_from_classloader(u, loader))) { + LOADER_DEC(); + return NULL; + } + LOADER_DEC(); + LOADER_ASSERT(comp->loaded); + if (opt_eager) + if (!link_class(c)) + return NULL; + + /* the array's flags are that of the component class */ + c->flags = (comp->flags & ~ACC_INTERFACE) | ACC_FINAL | ACC_ABSTRACT; + c->classloader = comp->classloader; + break; + + default: + /* c is an array of a primitive type */ -*******************************************************************************/ + /* check for cases like `[II' */ + if (namelen > 2) { + *exceptionptr = new_noclassdeffounderror(c->name); + return NULL; + } -#if 0 -/* XXX TWISTI: i think we do not need this */ -void loader_initclasses () -{ - classinfo *c; - -#if defined(USE_THREADS) && defined(NATIVE_THREADS) - pthread_mutex_lock(&compiler_mutex); -#endif + /* the accessibility of the array class is public (VM Spec 5.3.3) */ + c->flags = ACC_PUBLIC | ACC_FINAL | ACC_ABSTRACT; + c->classloader = NULL; + } - intsDisable(); /* schani */ + LOADER_ASSERT(class_java_lang_Object); + LOADER_ASSERT(class_java_lang_Cloneable); + LOADER_ASSERT(class_java_io_Serializable); - if (makeinitializations) { - c = list_first(&linkedclasses); - while (c) { - class_init(c); - c = list_next(&linkedclasses, c); - } - } + /* setup the array class */ - intsRestore(); /* schani */ - -#if defined(USE_THREADS) && defined(NATIVE_THREADS) - pthread_mutex_unlock(&compiler_mutex); -#endif -} -#endif + c->super.cls = class_java_lang_Object; + c->interfacescount = 2; + c->interfaces = MNEW(classref_or_classinfo, 2); -static void loader_compute_class_values(classinfo *c) -{ - classinfo *subs; + if (opt_eager) { + classinfo *tc; - c->vftbl->baseval = ++classvalue; + tc = class_java_lang_Cloneable; + LOADER_ASSERT(tc->loaded); + list_addfirst(&unlinkedclasses, tc); + c->interfaces[0].cls = tc; - subs = c->sub; - while (subs != NULL) { - loader_compute_class_values(subs); - subs = subs->nextsub; - } - c->vftbl->diffval = classvalue - c->vftbl->baseval; - -/* - { - int i; - for (i = 0; i < c->index; i++) - printf(" "); - printf("%3d %3d ", (int) c->vftbl->baseval, c->vftbl->diffval); - utf_display(c->name); - printf("\n"); + tc = class_java_io_Serializable; + LOADER_ASSERT(tc->loaded); + list_addfirst(&unlinkedclasses, tc); + c->interfaces[1].cls = tc; + + } else { + c->interfaces[0].cls = class_java_lang_Cloneable; + c->interfaces[1].cls = class_java_io_Serializable; } -*/ -} + c->methodscount = 1; + c->methods = MNEW(methodinfo, c->methodscount); -void loader_compute_subclasses() -{ - classinfo *c; - -#if defined(USE_THREADS) && !defined(NATIVE_THREADS) - intsDisable(); /* schani */ -#endif + classrefs = MNEW(constant_classref, 2); + CLASSREF_INIT(classrefs[0], c, c->name); + CLASSREF_INIT(classrefs[1], c, utf_java_lang_Object); - c = list_first(&linkedclasses); - while (c) { - if (!(c->flags & ACC_INTERFACE)) { - c->nextsub = 0; - c->sub = 0; - } - c = list_next(&linkedclasses, c); - } + /* create descriptor for clone method */ + /* we need one paramslot which is reserved for the 'this' parameter */ + clonedesc = NEW(methoddesc); + clonedesc->returntype.type = TYPE_ADDRESS; + clonedesc->returntype.classref = classrefs + 1; + clonedesc->returntype.arraydim = 0; + /* initialize params to "empty", add real params below in + descriptor_params_from_paramtypes */ + clonedesc->paramcount = 0; + clonedesc->paramslots = 0; + clonedesc->paramtypes[0].classref = classrefs + 0; - c = list_first(&linkedclasses); - while (c) { - if (!(c->flags & ACC_INTERFACE) && (c->super != NULL)) { - c->nextsub = c->super->sub; - c->super->sub = c; - } - c = list_next(&linkedclasses, c); - } + /* create methodinfo */ + + clone = c->methods; + MSET(clone, 0, methodinfo, 1); - classvalue = 0; -#if defined(USE_THREADS) && defined(NATIVE_THREADS) - cast_lock(); -#endif - loader_compute_class_values(class_java_lang_Object); #if defined(USE_THREADS) && defined(NATIVE_THREADS) - cast_unlock(); + initObjectLock(&clone->header); #endif -#if defined(USE_THREADS) && !defined(NATIVE_THREADS) - intsRestore(); /* schani */ -#endif -} + /* if you delete the ACC_NATIVE below, set clone->maxlocals=1 (interpreter + related) */ + clone->flags = ACC_PUBLIC | ACC_NATIVE; + clone->name = utf_clone; + clone->descriptor = utf_void__java_lang_Object; + clone->parseddesc = clonedesc; + clone->class = c; + clone->monoPoly = MONO; + /* parse the descriptor to get the register allocation */ -/******************** function classloader_buffer ****************************** - - sets buffer for reading classdata + if (!descriptor_params_from_paramtypes(clonedesc, clone->flags)) + return false; -*******************************************************************************/ + clone->entrypoint = + codegen_createnativestub((functionptr) &builtin_clone_array, clone); -void classload_buffer(u1 *buf, int len) -{ - classbuffer = buf; - classbuffer_size = len; - classbuf_pos = buf - 1; + /* XXX: field: length? */ + + /* array classes are not loaded from class files */ + + c->loaded = true; + c->parseddescs = (u1 *) clonedesc; + c->parseddescsize = sizeof(methodinfo); + c->classrefs = classrefs; + c->classrefcount = 1; + + /* insert class into the loaded class cache */ + /* XXX free classinfo if NULL returned? */ + + return classcache_store(loader,c,true); } -/******************** Function: loader_close *********************************** +/* loader_close **************************************************************** - Frees all resources + Frees all resources. *******************************************************************************/ -void loader_close() +void loader_close(void) { - classinfo *c; - - while ((c = list_first(&unloadedclasses))) { - list_remove(&unloadedclasses, c); - class_free(c); - } - while ((c = list_first(&unlinkedclasses))) { - list_remove(&unlinkedclasses, c); - class_free(c); - } - while ((c = list_first(&linkedclasses))) { - list_remove(&linkedclasses, c); - class_free(c); - } + /* empty */ }