verifier documentation
[cacao.git] / loader.c
index 0795178b374f0fe92e171ba1c63fef6c230b5d48..a73597d58afc442f97a396b020caf735be57d53d 100644 (file)
--- a/loader.c
+++ b/loader.c
             Mark Probst
                        Edwin Steiner
 
-   $Id: loader.c 758 2003-12-13 22:30:00Z twisti $
+   $Id: loader.c 881 2004-01-13 19:57:08Z edwin $
 
 */
 
 
+#include <stdlib.h>
 #include <string.h>
 #include <assert.h>
 #include <sys/stat.h>
@@ -71,7 +72,8 @@ int count_extable_len = 0;
 int count_class_loads = 0;
 int count_class_inits = 0;
 
-static s4 interfaceindex;       /* sequential numbering of interfaces         */ 
+static s4 interfaceindex;       /* sequential numbering of interfaces         */
+static s4 classvalue;
 
 list unloadedclasses;       /* list of all referenced but not loaded classes  */
 list unlinkedclasses;       /* list of all loaded but not linked classes      */
@@ -85,6 +87,7 @@ static utf *utf_constantvalue;                /* ConstantValue           */
 static utf *utf_code;                      /* Code                    */
 static utf *utf_finalize;                  /* finalize                */
 static utf *utf_fidesc;                    /* ()V changed             */
+static utf *utf_init;                          /* <init>                  */
 static utf *utf_clinit;                    /* <clinit>                */
 static utf *utf_initsystemclass;       /* initializeSystemClass   */
 static utf *utf_systemclass;           /* java/lang/System        */
@@ -92,11 +95,9 @@ 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        */
 
 
-#ifdef USE_ZLIB
-static unzFile uf = 0;
-#endif
 
 
 utf* clinit_desc(){
@@ -134,11 +135,18 @@ static classinfo *class_java_lang_ArithmeticException;
 static classinfo *class_java_lang_ArrayStoreException;
 static classinfo *class_java_lang_ThreadDeath;
 
-static methodinfo method_clone_array;
+utf *array_packagename = NULL;
 
 static int loader_inited = 0;
 
 
+/********************************************************************
+   list of classpath entries (either filesystem directories or 
+   ZIP/JAR archives
+********************************************************************/
+static classpath_info *classpath_entries=0;
+
+
 /******************************************************************************
 
    structure for primitive classes: contains the class for wrapping the 
@@ -151,15 +159,17 @@ static int loader_inited = 0;
  * 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 }};
+       { 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 **************************************/
 
@@ -290,10 +300,120 @@ static double suck_double()
 
 void suck_init(char *cpath)
 {
+       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;
+                               }
+#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);
+                               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;
+                               }
+#else
+                               panic("Zip/JAR 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';
+                                       filenamelen++;
+                               }
+                       
+                               tmp->filepath.filename=filename;
+                               tmp->filepath.pathlen=filenamelen;                              
+                               filename=0;
+                       }
+
+               if (tmp) {
+                       if (insertAfter) {
+                               insertAfter->filepath.next=tmp;
+                       } else {
+                               classpath_entries=tmp;  
+                       }
+                       insertAfter=tmp;
+               }
+       }
+               if ((*end)==':') start=end+1; else start=end;
+       
+       
+       if (filename!=0) free(filename);
 }
 
+}
 
 /************************** function suck_start ********************************
 
@@ -306,111 +426,64 @@ void suck_init(char *cpath)
 
 bool suck_start(utf *classname)
 {
-
-#define MAXFILENAME 1000               /* maximum length of a filename           */
-       
-       char filename[MAXFILENAME+10];  /* room for '.class'                      */    
-       char *pathpos;                  /* position in searchpath                 */
-       char c, *utf_ptr;               /* pointer to the next utf8-character     */
+       classpath_info *currPos;
+       char *utf_ptr;
+       char c;
+       char filename[CLASSPATH_MAXFILENAME+10];  /* room for '.class'                      */  
+       int  filenamelen=0;
        FILE *classfile;
-       int  filenamelen, err;
+       int  err;
        struct stat buffer;
-       int isZip;
-
-       if (classbuffer)                /* classbuffer is already valid */
-               return true;
-
-       pathpos = classpath;
-       
-       while (*pathpos) {
-
-               /* skip path separator */
-
-               while (*pathpos == ':')
-                       pathpos++;
-               /* extract directory from searchpath */
 
-               filenamelen = 0;
-               while ((*pathpos) && (*pathpos != ':')) {
-                   PANICIF (filenamelen >= MAXFILENAME, "Filename too long");
-                       filename[filenamelen++] = *(pathpos++);
-                       }
+       if (classbuffer) return true; /* classbuffer is already valid */
 
-               isZip = 0;
-               if (filenamelen > 4) {
-                       if ( ((filename[filenamelen - 1] == 'p') || (filename[filenamelen - 1] == 'P')) &
-                            ((filename[filenamelen - 2] == 'i') || (filename[filenamelen - 2] == 'I')) &
-                                ((filename[filenamelen - 3] == 'z') || (filename[filenamelen - 3] == 'Z')) ) {
-                               isZip = 1;
-                       }
-               }
-
-               if (isZip) {
+       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
-                       filename[filenamelen++] = '\0';
-                       if (uf == 0) uf = unzOpen(filename);
-                       if (uf != 0) {
-                               utf_ptr = classname->text;
-                               filenamelen = 0;
-                               while (utf_ptr < utf_end(classname)) {
-                                       PANICIF (filenamelen >= MAXFILENAME, "Filename too long");
-                                       c = *utf_ptr++;
-                                       if ((c <= ' ' || c > 'z') && (c != '/'))     /* invalid character */ 
-                                               c = '?'; 
-                                       filename[filenamelen++] = c;    
-                               }
-                               strcpy(filename + filenamelen, ".class");
-                               if (cacao_locate(uf,classname) == UNZ_OK) {
-                                       unz_file_info file_info;
-                                       log_text("Class found in zip file");
-                                       if (unzGetCurrentFileInfo(uf, &file_info, filename,
-                                                                                                 sizeof(filename), NULL, 0, NULL, 0) == UNZ_OK) {
-                                               if (unzOpenCurrentFile(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(uf, classbuffer, classbuffer_size) == classbuffer_size) {
-                                                               unzCloseCurrentFile(uf);
-                                                               return true;
-                                                       } else {
-                                                               MFREE(classbuffer, u1, classbuffer_size);
-                                                               log_text("Error while unzipping");
-                                                       }
-                                               } else log_text("Error while opening file in archive");
-                                       } else log_text("Error while retrieving fileinfo");
-                               }
-                               unzCloseCurrentFile(uf);
-
-                       }
-#endif                 
-               } else {
-                       filename[filenamelen++] = '/';  
-   
-                       /* add classname to filename */
-
-                       utf_ptr = classname->text;
-                       while (utf_ptr < utf_end(classname)) {
-                               PANICIF (filenamelen >= MAXFILENAME, "Filename too long");
-                               c = *utf_ptr++;
-                               if ((c <= ' ' || c > 'z') && (c != '/'))     /* invalid character */ 
-                                       c = '?'; 
-                               filename[filenamelen++] = c;    
+               if (currPos->filepath.type==CLASSPATH_ARCHIVE) {
+                       if (cacao_locate(currPos->archive.uf,classname) == 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);
+                                                       log_text("Error while unzipping");
+                                               }
+                                       } else log_text("Error while opening file in archive");
+                               } else log_text("Error while retrieving fileinfo");
                        }
-       
-                       /* add suffix */
-
-                       strcpy(filename + filenamelen, ".class");
+                       unzCloseCurrentFile(currPos->archive.uf);
 
-                       classfile = fopen(filename, "r");
+               } 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 */
 
                                /* determine size of classfile */
 
                                /* dolog("File: %s",filename); */
 
-                               err = stat(filename, &buffer);
+                               err = stat(currPos->filepath.filename, &buffer);
 
                                if (!err) {                                /* read classfile data */                            
                                        classbuffer_size = buffer.st_size;                              
@@ -421,15 +494,18 @@ bool suck_start(utf *classname)
                                        return true;
                                }
                        }
+#ifdef USE_ZLIB
                }
+#endif
        }
+
        if (verbose) {
                dolog("Warning: Can not open class file '%s'", filename);
        }
 
        return false;
-}
 
+}
 
 /************************** function suck_stop *********************************
 
@@ -447,9 +523,10 @@ void suck_stop()
 
        if (classdata_left > 0) {
                /* surplus */           
-               dolog("There are %d access bytes at end of classfile",
+               dolog("There are %d extra bytes at end of classfile",
                                classdata_left);
-               /* XXX panic? */
+               /* The JVM spec disallows extra bytes. */
+               panic("Extra bytes at end of classfile");
        }
 
        /* free memory */
@@ -463,8 +540,6 @@ void suck_stop()
 /******************* Some support functions ***********************************/
 /******************************************************************************/
 
-
-
 void fprintflags (FILE *fp, u2 f)
 {
    if ( f & ACC_PUBLIC )       fprintf (fp," PUBLIC");
@@ -480,8 +555,10 @@ void fprintflags (FILE *fp, u2 f)
    if ( f & ACC_ABSTRACT )     fprintf (fp," ABSTRACT");
 }
 
+
 /********** internal function: printflags  (only for debugging) ***************/
-void printflags (u2 f)
+
+void printflags(u2 f)
 {
    if ( f & ACC_PUBLIC )       printf (" PUBLIC");
    if ( f & ACC_PRIVATE )      printf (" PRIVATE");
@@ -503,7 +580,7 @@ void printflags (u2 f)
 
 *******************************************************************************/
 
-static void skipattribute ()
+static void skipattribute()
 {
        u4 len;
        suck_u2 ();
@@ -511,6 +588,7 @@ static void skipattribute ()
        skip_nbytes(len);       
 }
 
+
 /********************** Function: skipattributebody ****************************
 
        skips an attribute after the 16 bit reference to attribute_name has already
@@ -518,37 +596,39 @@ static void skipattribute ()
        
 *******************************************************************************/
 
-static void skipattributebody ()
+static void skipattributebody()
 {
        u4 len;
        len = suck_u4();
        skip_nbytes(len);
 }
 
+
 /************************* Function: skipattributes ****************************
 
        skips num attribute structures
        
 *******************************************************************************/
 
-static void skipattributes (u4 num)
+static void skipattributes(u4 num)
 {
        u4 i;
        for (i = 0; i < num; i++)
                skipattribute();
 }
 
+
 /******************** function: innerclass_getconstant ************************
 
     like class_getconstant, but if cptags is ZERO null is returned                                      
        
 *******************************************************************************/
 
-voidptr innerclass_getconstant (classinfo *c, u4 pos, u4 ctype) 
+voidptr innerclass_getconstant(classinfo *c, u4 pos, u4 ctype) 
 {
        /* invalid position in constantpool */
-       if (pos >= c->cpcount) 
-               panic ("Attempt to access constant outside range");
+       if (pos >= c->cpcount)
+               panic("Attempt to access constant outside range");
 
        /* constantpool entry of type 0 */      
        if (!c->cptags[pos])
@@ -556,39 +636,42 @@ voidptr innerclass_getconstant (classinfo *c, u4 pos, u4 ctype)
 
        /* 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] );
-               }
+               error("Type mismatch on constant: %d requested, %d here (innerclass_getconstant)",
+                         (int) ctype, (int) c->cptags[pos] );
+       }
                
        return c->cpinfos[pos];
 }
 
+
 /************************ function: attribute_load ****************************
 
     read attributes from classfile
        
 *******************************************************************************/
 
-static void attribute_load (u4 num, classinfo *c)
+static void attribute_load(u4 num, classinfo *c)
 {
-       u4 i,j;
+       u4 i, j;
 
        for (i = 0; i < num; i++) {
-               /* retrieve attribute name */   
-               utf *aname = class_getconstant (c, suck_u2(), CONSTANT_Utf8);
+               /* retrieve attribute name */
+               utf *aname = class_getconstant(c, suck_u2(), CONSTANT_Utf8);
 
-               if ( aname == utf_innerclasses)  {                      
+               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);
+                       c->innerclass = MNEW(innerclassinfo, c->innerclasscount);
 
-                       for (j=0;j<c->innerclasscount;j++) {
-                               
+                       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, 
@@ -599,15 +682,17 @@ static void attribute_load (u4 num, classinfo *c)
                                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      */
+                               info->flags = suck_u2();                                                  /* access_flags bitmask      */
                        }
+
                } else {
                        /* unknown attribute */
-                       skipattributebody ();
+                       skipattributebody();
                }
        }
 }
 
+
 /******************* function: checkfielddescriptor ****************************
 
        checks whether a field-descriptor is valid and aborts otherwise
@@ -622,6 +707,8 @@ static void checkfielddescriptor (char *utf_ptr, char *end_pos)
                                                  | CLASSLOAD_NULLPRIMITIVE
                                                  | CLASSLOAD_NOVOID
                                                  | CLASSLOAD_CHECKEND);
+       
+       /* XXX use the following if -noverify */
 #if 0
        char *tstart;  /* pointer to start of classname */
        char ch;
@@ -659,33 +746,49 @@ static void checkfielddescriptor (char *utf_ptr, char *end_pos)
 
     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 void checkmethoddescriptor (utf *d)
+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 != ')') {
+               /* XXX 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 return type in method descriptor");
+       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
        /* XXX check length */
        /* check arguments */
@@ -777,101 +880,125 @@ void print_arraydescriptor(FILE *file, arraydescriptor *desc)
 
 *******************************************************************************/
 
-static void field_load (fieldinfo *f, classinfo *c)
+#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");
+               }
 
-       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           */
-       f -> type = jtype = desc_to_type (f->descriptor);                  /* data type                   */
-       f -> offset = 0;                                                   /* offset from start of object */
-       f -> class = c;
+               /* 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;                              
-/*                           heap_addreference (&(f->value.a));           /* make global reference (GC)  */
-                             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 
+#endif
        }
 
        /* read attributes */
        attrnum = suck_u2();
-       for (i=0; i<attrnum; i++) {
-               u4 pindex;
+       for (i = 0; i < attrnum; i++) {
                utf *aname;
 
-               aname = class_getconstant (c, suck_u2(), CONSTANT_Utf8);
+               aname = class_getconstant(c, suck_u2(), CONSTANT_Utf8);
                
-               if ( aname != utf_constantvalue ) {
+               if (aname != utf_constantvalue) {
                        /* unknown attribute */
-                       skipattributebody ();
-                       }
-               else {
+                       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");
                        
-                       /* skip attribute length */
-                       suck_u4();
                        /* 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_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_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_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_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;
+                       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");
-
-                               }
-
+                       default: 
+                               log_text ("Invalid Constant - Type");
                        }
                }
+       }
 }
 
 
@@ -914,6 +1041,7 @@ void field_display(fieldinfo *f)
 static void method_load(methodinfo *m, classinfo *c)
 {
        u4 attrnum, i, e;
+       int argcount;
        
 #ifdef STATISTICS
        count_all_methods++;
@@ -923,9 +1051,48 @@ static void method_load(methodinfo *m, classinfo *c)
        
        m->flags = suck_u2();
        m->name = class_getconstant(c, suck_u2(), CONSTANT_Utf8);
-       m->descriptor = class_getconstant(c, suck_u2(), CONSTANT_Utf8);
-       checkmethoddescriptor(m->descriptor);
+
+       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 */
+               /* XXX could check if <clinit> is STATIC */
+               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;
@@ -961,12 +1128,18 @@ static void method_load(methodinfo *m, classinfo *c)
 
                } else {
                        u4 codelen;
-                       if (m->jcode)
-                               panic("Two code-attributes for one method!");
+                       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");
@@ -1003,6 +1176,9 @@ static void method_load(methodinfo *m, classinfo *c)
                        skipattributes(suck_u2());
                }
        }
+
+       if (!m->jcode && (m->flags & (ACC_ABSTRACT | ACC_NATIVE)) == 0)
+               panic("Method missing Code attribute");
 }
 
 
@@ -1080,7 +1256,8 @@ static bool method_canoverwrite (methodinfo *m, methodinfo *old)
 
 voidptr class_getconstant(classinfo *c, u4 pos, u4 ctype)
 {
-       /* invalid position in constantpool */  
+       /* invalid position in constantpool */
+       /* (pos == 0 is caught by type comparison) */
        if (pos >= c->cpcount)
                panic("Attempt to access constant outside range");
 
@@ -1168,12 +1345,15 @@ static void class_loadcpool(classinfo *c)
        forward_nameandtype *forward_nameandtypes = NULL;
        forward_fieldmethint *forward_fieldmethints = NULL;
 
-       /* number of entries in the constant_pool table  */
+       /* number of entries in the constant_pool table plus one */
        u4 cpcount       = c -> cpcount = suck_u2();
        /* allocate memory */
        u1 *cptags       = c -> cptags  = MNEW (u1, cpcount);
        voidptr *cpinfos = c -> cpinfos = MNEW (voidptr, cpcount);
 
+       if (!cpcount)
+               panic("Invalid constant_pool_count (0)");
+       
 #ifdef STATISTICS
        count_const_pool_len += (sizeof(voidptr) + 1) * cpcount;
 #endif
@@ -1299,6 +1479,8 @@ static void class_loadcpool(classinfo *c)
                                cptags [idx] = CONSTANT_Long;
                                cpinfos [idx] = cl;
                                idx += 2;
+                               if (idx > cpcount)
+                                       panic("Long constant exceeds constant pool");
                                break;
                                }
                        
@@ -1313,6 +1495,8 @@ static void class_loadcpool(classinfo *c)
                                cptags [idx] = CONSTANT_Double;
                                cpinfos [idx] = cd;
                                idx += 2;
+                               if (idx > cpcount)
+                                       panic("Double constant exceeds constant pool");
                                break;
                                }
                                
@@ -1323,8 +1507,12 @@ static void class_loadcpool(classinfo *c)
                                cptags [idx]  = CONSTANT_Utf8;
                                /* validate the string */
                                ASSERT_LEFT(length);
-                               if (!is_valid_utf(classbuf_pos+1, classbuf_pos+1+length))
-                                       panic("Invalid UTF-8 string"); 
+                               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 */
@@ -1348,6 +1536,9 @@ static void class_loadcpool(classinfo *c)
                utf *name =
                  class_getconstant (c, forward_classes -> name_index, CONSTANT_Utf8);
 
+               if (opt_verify && !is_valid_name_utf(name))
+                       panic("Class reference with invalid name");
+
                cptags  [forward_classes -> thisindex] = CONSTANT_Class;
                /* retrieve class from class-table */
                cpinfos [forward_classes -> thisindex] = class_new (name);
@@ -1383,7 +1574,16 @@ static void class_loadcpool(classinfo *c)
                   (c, forward_nameandtypes -> name_index, CONSTANT_Utf8);
                cn -> descriptor = class_getconstant
                   (c, forward_nameandtypes -> sig_index, CONSTANT_Utf8);
-                
+
+               if (opt_verify) {
+                       /* check name */
+                       if (!is_valid_name_utf(cn->name))
+                               panic("NameAndType with invalid name");
+                       /* disallow referencing <clinit> among others */
+                       if (cn->name->text[0] == '<' && cn->name != utf_init)
+                               panic("NameAndType with invalid special name");
+               }
+
                cptags   [forward_nameandtypes -> thisindex] = CONSTANT_NameAndType;
                cpinfos  [forward_nameandtypes -> thisindex] = cn;
                
@@ -1431,7 +1631,6 @@ static void class_loadcpool(classinfo *c)
                                         break;
                case CONSTANT_InterfaceMethodref: 
                case CONSTANT_Methodref: /* check validity of descriptor */
-                       /* XXX check special names (<init>) */
                                         checkmethoddescriptor (fmi->descriptor);
                                         break;
                }               
@@ -1504,15 +1703,46 @@ static int class_load(classinfo *c)
        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) {
+                       /* XXX 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 ((c->flags & (ACC_FINAL | ACC_SUPER)) != 0)
+                       panic("Interface class has invalid flags");
+       }
+       if ((c->flags & (ACC_ABSTRACT | ACC_FINAL)) == (ACC_ABSTRACT | ACC_FINAL))
+               panic("Class is declared both abstract and final");
+
        /* this class */
-       suck_u2();       
+       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);
 
+               /* 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");
+               }
        } 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 */
@@ -1540,6 +1770,91 @@ static int class_load(classinfo *c)
                method_load(&(c->methods[i]), c);
        }
 
+       /* 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;
+
+               /* Allocate hashtable */
+               len = c->methodscount;
+               if (len < c->fieldscount) len = c->fieldscount;
+               hashlen = 5 * len;
+               hashtab = MNEW(u2,(hashlen + len));
+               next = hashtab + hashlen;
+
+               /* Determine bitshift (to get good hash values) */
+               if (!shift) {
+                       len = sizeof(utf);
+                       while (len) {
+                               len >>= 1;
+                               shift++;
+                       }
+               }
+
+               /* Check fields */
+               memset(hashtab,0,sizeof(u2) * (hashlen + len));
+               for (i = 0; i<c->fieldscount; ++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; 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;
+                       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);
+                       }
+                       /* else dolog("HASHLUCKY"); */
+                       hashtab[index] = i+1;
+               }
+               
+               MFREE(hashtab,u2,(hashlen + len));
+       }
+
 #ifdef STATISTICS
        count_class_infos += sizeof(classinfo*) * c->interfacescount;
        count_class_infos += sizeof(fieldinfo) * c->fieldscount;
@@ -1580,7 +1895,7 @@ static s4 class_highestinterface(classinfo *c)
                char logtext[MAXLOGTEXT];
                sprintf(logtext, "Interface-methods count requested for non-interface:  ");
        utf_sprint(logtext + strlen(logtext), c->name);
-       error(logtext);
+       error("%s",logtext);
        }
     
     h = c->index;
@@ -1662,7 +1977,7 @@ void class_new_array(classinfo *c)
        /* XXX remove */ /* dolog("class_new_array: %s",c->name->text); */
 
        /* Array classes are not loaded from classfiles. */
-       list_remove (&unloadedclasses, c);
+       list_remove(&unloadedclasses, c);
 
        /* Check array class name */
        namelen = c->name->blength;
@@ -1678,7 +1993,7 @@ void class_new_array(classinfo *c)
 
          case 'L':
                  /* c is an array of objects. */
-                 if (namelen < 4 || c->name->text[namelen-1] != ';')
+                 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;
@@ -1768,11 +2083,13 @@ static arraydescriptor *class_link_array(classinfo *c)
                
                compvftbl = comp->vftbl;
                if (!compvftbl)
-                       panic("Component class has no vftbl.");
+                       panic("Component class has no vftbl");
                desc->componentvftbl = compvftbl;
                
                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;
                }
@@ -1781,36 +2098,52 @@ static arraydescriptor *class_link_array(classinfo *c)
                        desc->dimension = 1;
                        desc->elementtype = ARRAYTYPE_OBJECT;
                }
-       }
-       else {
+
+       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;
-                 case 'B': desc->arraytype = ARRAYTYPE_BYTE;
-                           desc->dataoffset = OFFSET(java_bytearray,data);
-                               desc->componentsize = sizeof(u1); break;
-                 case 'C': desc->arraytype = ARRAYTYPE_CHAR;
-                           desc->dataoffset = OFFSET(java_chararray,data);
-                               desc->componentsize = sizeof(u2); break;
-                 case 'D': desc->arraytype = ARRAYTYPE_DOUBLE;
-                           desc->dataoffset = OFFSET(java_doublearray,data);
-                               desc->componentsize = sizeof(double); break;
-                 case 'F': desc->arraytype = ARRAYTYPE_FLOAT;
-                           desc->dataoffset = OFFSET(java_floatarray,data);
-                               desc->componentsize = sizeof(float); break;
-                 case 'I': desc->arraytype = ARRAYTYPE_INT;
-                           desc->dataoffset = OFFSET(java_intarray,data);
-                               desc->componentsize = sizeof(s4); break;
-                 case 'J': desc->arraytype = ARRAYTYPE_LONG;
-                           desc->dataoffset = OFFSET(java_longarray,data);
-                               desc->componentsize = sizeof(s8); break;
-                 case 'S': desc->arraytype = ARRAYTYPE_SHORT;
-                           desc->dataoffset = OFFSET(java_shortarray,data);
-                               desc->componentsize = sizeof(s2); break;
-                 default:
-                         panic("Invalid array class name");
+               case 'Z': desc->arraytype = ARRAYTYPE_BOOLEAN;
+                       desc->dataoffset = OFFSET(java_booleanarray,data);
+                       desc->componentsize = sizeof(u1);
+                       break;
+
+               case 'B': desc->arraytype = ARRAYTYPE_BYTE;
+                       desc->dataoffset = OFFSET(java_bytearray,data);
+                       desc->componentsize = sizeof(u1);
+                       break;
+
+               case 'C': desc->arraytype = ARRAYTYPE_CHAR;
+                       desc->dataoffset = OFFSET(java_chararray,data);
+                       desc->componentsize = sizeof(u2);
+                       break;
+
+               case 'D': desc->arraytype = ARRAYTYPE_DOUBLE;
+                       desc->dataoffset = OFFSET(java_doublearray,data);
+                       desc->componentsize = sizeof(double);
+                       break;
+
+               case 'F': desc->arraytype = ARRAYTYPE_FLOAT;
+                       desc->dataoffset = OFFSET(java_floatarray,data);
+                       desc->componentsize = sizeof(float);
+                       break;
+
+               case 'I': desc->arraytype = ARRAYTYPE_INT;
+                       desc->dataoffset = OFFSET(java_intarray,data);
+                       desc->componentsize = sizeof(s4);
+                       break;
+
+               case 'J': desc->arraytype = ARRAYTYPE_LONG;
+                       desc->dataoffset = OFFSET(java_longarray,data);
+                       desc->componentsize = sizeof(s8);
+                       break;
+
+               case 'S': desc->arraytype = ARRAYTYPE_SHORT;
+                       desc->dataoffset = OFFSET(java_shortarray,data);
+                       desc->componentsize = sizeof(s2);
+                       break;
+
+               default:
+                       panic("Invalid array class name");
                }
                
                desc->componentvftbl = NULL;
@@ -1863,6 +2196,13 @@ void class_link(classinfo *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");
+               }
        }
        
        /*  check super class */
@@ -1870,7 +2210,7 @@ void class_link(classinfo *c)
        if (super == NULL) {          /* class java.long.Object */
                c->index = 0;
         c->classUsed = USED;     /* Object class is always used CO-RT*/
-               c -> impldBy = NULL;
+               c->impldBy = NULL;
                c->instancesize = sizeof(java_objectheader);
                
                vftbllength = supervftbllength = 0;
@@ -1884,13 +2224,21 @@ void class_link(classinfo *c)
                        return; 
                }
 
+               if ((super->flags & ACC_INTERFACE) != 0)
+                       panic("Interface specified as super class");
+
                /* 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; 
                        }
+
+               /* 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++;
@@ -1923,6 +2271,8 @@ void class_link(classinfo *c)
                                int j;
                                for (j = 0; j < sc->methodscount; j++) {
                                        if (method_canoverwrite(m, &(sc->methods[j]))) {
+                                               if ((sc->methods[j].flags & ACC_FINAL) != 0)
+                                                       panic("Trying to overwrite final method");
                                                m->vftblindex = sc->methods[j].vftblindex;
                                                goto foundvftblindex;
                                        }
@@ -2436,7 +2786,6 @@ bool class_issubclass(classinfo *sub, classinfo *super)
 void class_init(classinfo *c)
 {
        methodinfo *m;
-       java_objectheader *exceptionptr;
        s4 i;
 #ifdef USE_THREADS
        int b;
@@ -2453,10 +2802,31 @@ void class_init(classinfo *c)
        count_class_inits++;
 #endif
 
-       if (c->super)
-               class_init (c->super);
-       for (i = 0; i < c->interfacescount; i++)
+       /* 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);
+               }
+               class_init(c->super);
+       }
+
+       /* 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);
+               }
                class_init(c->interfaces[i]);  /* real */
+       }
 
        m = class_findmethod(c, utf_clinit, utf_fidesc);
        if (!m) {
@@ -2486,20 +2856,22 @@ void class_init(classinfo *c)
        blockInts = 0;
 #endif
 
-       exceptionptr = asm_calljavamethod(m, NULL, NULL, NULL, NULL);
+       /* now call the initializer */
+       asm_calljavafunction(m, NULL, NULL, NULL, NULL);
 
 #ifdef USE_THREADS
        assert(blockInts == 0);
        blockInts = b;
 #endif
 
-       if (exceptionptr) {
-               printf("#### Initializer of ");
-               utf_display(c->name);
-               printf(" has thrown: ");
-               utf_display(exceptionptr->vftbl->class->name);
+       /* 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) {
@@ -2508,6 +2880,7 @@ void class_init(classinfo *c)
                utf_sprint(logtext + strlen(logtext), c->name);
                log_text(logtext);
        }
+
        if (c->name == utf_systemclass) {
                /* class java.lang.System requires explicit initialization */
 
@@ -2530,16 +2903,16 @@ void class_init(classinfo *c)
                blockInts = 0;
 #endif
 
-               exceptionptr = asm_calljavamethod(m, NULL, NULL, NULL, NULL);
+               asm_calljavafunction(m, NULL, NULL, NULL, NULL);
 
 #ifdef USE_THREADS
                assert(blockInts == 0);
                blockInts = b;
 #endif
 
-               if (exceptionptr) {
+               if (*exceptionptr) {
                        printf("#### initializeSystemClass has thrown: ");
-                       utf_display(exceptionptr->vftbl->class->name);
+                       utf_display((*exceptionptr)->vftbl->class->name);
                        printf("\n");
                        fflush(stdout);
                }
@@ -2818,7 +3191,7 @@ classinfo *loader_load(utf *topname)
        s8 starttime = 0;
        s8 stoptime = 0;
        classinfo *notlinkable;
-       
+
 #if defined(USE_THREADS) && defined(NATIVE_THREADS)
        pthread_mutex_lock(&compiler_mutex);
 #endif
@@ -2866,7 +3239,7 @@ classinfo *loader_load(utf *topname)
                                if (linkverbose)
                                        dolog("Cannot resolve linking dependencies");
                                top = NULL;
-                               if (!exceptionptr)
+                               if (!*exceptionptr)
                                        throw_linkageerror_message(c->name);
                                break;
                        }
@@ -2917,6 +3290,7 @@ classinfo *loader_load(utf *topname)
        return top; 
 }
 
+
 /****************** Function: loader_load_sysclass ****************************
 
        Loads and links the class desired class and each class and interface
@@ -2929,12 +3303,12 @@ classinfo *loader_load(utf *topname)
 
 *******************************************************************************/
 
-classinfo *loader_load_sysclass(classinfo **top,utf *topname)
+classinfo *loader_load_sysclass(classinfo **top, utf *topname)
 {
        classinfo *cls;
 
        if ((cls = loader_load(topname)) == NULL) {
-               log_plain("Could not important system class: ");
+               log_plain("Could not load important system class: ");
                log_plain_utf(topname);
                log_nl();
                panic("Could not load important system class");
@@ -2945,6 +3319,7 @@ classinfo *loader_load_sysclass(classinfo **top,utf *topname)
        return cls;
 }
 
+
 /**************** function: create_primitive_classes ***************************
 
        create classes representing primitive types 
@@ -3194,12 +3569,12 @@ static void create_pseudo_classes()
 
     /* pseudo class representing new uninitialized objects */
     
-    pseudo_class_New = class_new( utf_new_char("$NEW$") );
-    list_remove(&unloadedclasses,pseudo_class_New);
+    pseudo_class_New = class_new(utf_new_char("$NEW$"));
+    list_remove(&unloadedclasses, pseudo_class_New);
 
     pseudo_class_New->super = class_java_lang_Object;
 
-    list_addlast(&unlinkedclasses,pseudo_class_New);
+    list_addlast(&unlinkedclasses, pseudo_class_New);
     class_link(pseudo_class_New);      
 }
 
@@ -3211,15 +3586,13 @@ static void create_pseudo_classes()
 
 *******************************************************************************/
  
-void loader_init(u1 * stackbottom)
+void loader_init(u1 *stackbottom)
 {
        interfaceindex = 0;
        
-       log_text("Entering loader_init");
-       
-       list_init (&unloadedclasses, OFFSET(classinfo, listnode) );
-       list_init (&unlinkedclasses, OFFSET(classinfo, listnode) );
-       list_init (&linkedclasses, OFFSET(classinfo, listnode) );
+       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");
@@ -3227,6 +3600,7 @@ void loader_init(u1 * stackbottom)
        utf_code                = utf_new_char("Code");
        utf_finalize        = utf_new_char("finalize");
        utf_fidesc              = utf_new_char("()V");
+       utf_init                = utf_new_char("<init>");
        utf_clinit              = utf_new_char("<clinit>");
        utf_initsystemclass = utf_new_char("initializeSystemClass");
        utf_systemclass     = utf_new_char("java/lang/System");
@@ -3235,6 +3609,9 @@ void loader_init(u1 * stackbottom)
        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("<the array package>");
 
        /* create some important classes */
        /* These classes have to be created now because the classinfo
@@ -3245,7 +3622,7 @@ void loader_init(u1 * stackbottom)
        class_java_lang_Cloneable = class_new(utf_new_char("java/lang/Cloneable"));
        class_java_io_Serializable = class_new(utf_new_char("java/io/Serializable"));
 
-       log_text("loader_init: java/lang/Object");
+       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);
 
@@ -3254,7 +3631,7 @@ void loader_init(u1 * stackbottom)
        loader_load_sysclass(&class_java_lang_Throwable,
                                                 utf_new_char("java/lang/Throwable"));
 
-       log_text("loader_init:  loader_load: java/lang/ClassCastException");
+       if (verbose) log_text("loader_init:  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,
@@ -3286,41 +3663,33 @@ void loader_init(u1 * stackbottom)
                initLocks();
 #endif
 
-       log_text("loader_init: creating global proto_java_lang_ClassCastException");
+       if (verbose) log_text("loader_init: creating global proto_java_lang_ClassCastException");
        proto_java_lang_ClassCastException =
                builtin_new(class_java_lang_ClassCastException);
-/*     heap_addreference((void**) &proto_java_lang_ClassCastException); */
 
-       log_text("loader_init: proto_java_lang_ClassCastException has been initialized");
+       if (verbose) log_text("loader_init: proto_java_lang_ClassCastException has been initialized");
 
        proto_java_lang_NullPointerException =
                builtin_new(class_java_lang_NullPointerException);
-/*     heap_addreference((void**) &proto_java_lang_NullPointerException); */
-       log_text("loader_init: proto_java_lang_NullPointerException has been initialized");
+       if (verbose) log_text("loader_init: proto_java_lang_NullPointerException has been initialized");
 
        proto_java_lang_ArrayIndexOutOfBoundsException =
                builtin_new(class_java_lang_ArrayIndexOutOfBoundsException);
-/*     heap_addreference((void**) &proto_java_lang_ArrayIndexOutOfBoundsException); */
 
        proto_java_lang_NegativeArraySizeException =
                builtin_new(class_java_lang_NegativeArraySizeException);
-/*     heap_addreference((void**) &proto_java_lang_NegativeArraySizeException); */
 
        proto_java_lang_OutOfMemoryError =
                builtin_new(class_java_lang_OutOfMemoryError);
-/*     heap_addreference((void**) &proto_java_lang_OutOfMemoryError); */
 
        proto_java_lang_ArithmeticException =
                builtin_new(class_java_lang_ArithmeticException);
-/*     heap_addreference((void**) &proto_java_lang_ArithmeticException); */
 
        proto_java_lang_ArrayStoreException =
                builtin_new(class_java_lang_ArrayStoreException);
-/*     heap_addreference((void**) &proto_java_lang_ArrayStoreException); */
 
-       proto_java_lang_ThreadDeath =                             /* schani */
+       proto_java_lang_ThreadDeath =
                builtin_new(class_java_lang_ThreadDeath);
-/*     heap_addreference((void**) &proto_java_lang_ThreadDeath); */
 
        loader_inited = 1;
 }
@@ -3332,6 +3701,8 @@ void loader_init(u1 * stackbottom)
 
 *******************************************************************************/
 
+#if 0
+/* XXX TWISTI: i think we do not need this */
 void loader_initclasses ()
 {
        classinfo *c;
@@ -3343,12 +3714,12 @@ void loader_initclasses ()
        intsDisable();                     /* schani */
 
        if (makeinitializations) {
-               c = list_first (&linkedclasses);
+               c = list_first(&linkedclasses);
                while (c) {
-                       class_init (c);
-                       c = list_next (&linkedclasses, c);
-                       }
+                       class_init(c);
+                       c = list_next(&linkedclasses, c);
                }
+       }
 
        intsRestore();                      /* schani */
        
@@ -3356,8 +3727,8 @@ void loader_initclasses ()
        pthread_mutex_unlock(&compiler_mutex);
 #endif
 }
+#endif
 
-static s4 classvalue;
 
 static void loader_compute_class_values(classinfo *c)
 {
@@ -3397,16 +3768,16 @@ void loader_compute_subclasses()
                        c->nextsub = 0;
                        c->sub = 0;
                }
-               c = list_next (&linkedclasses, c);
+               c = list_next(&linkedclasses, c);
        }
 
-       c = list_first (&linkedclasses);
+       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);
+               c = list_next(&linkedclasses, c);
        }
 
        classvalue = 0;