* src/vm/suck.hpp (SuckClasspath): Added as list of classpath entries.
[cacao.git] / src / vm / loader.cpp
1 /* src/vm/loader.cpp - class loader functions
2
3    Copyright (C) 1996-2005, 2006, 2007, 2008
4    CACAOVM - Verein zur Foerderung der freien virtuellen Maschine CACAO
5
6    This file is part of CACAO.
7
8    This program is free software; you can redistribute it and/or
9    modify it under the terms of the GNU General Public License as
10    published by the Free Software Foundation; either version 2, or (at
11    your option) any later version.
12
13    This program is distributed in the hope that it will be useful, but
14    WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16    General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program; if not, write to the Free Software
20    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
21    02110-1301, USA.
22
23 */
24
25
26 #include "config.h"
27
28 #include <stdlib.h>
29 #include <string.h>
30 #include <assert.h>
31
32 #include "vm/types.h"
33
34 #include "mm/dumpmemory.hpp"
35 #include "mm/memory.hpp"
36
37 #include "native/llni.h"
38
39 #include "threads/mutex.hpp"
40
41 #include "toolbox/hashtable.h"
42 #include "toolbox/logging.hpp"
43
44 #include "vm/jit/builtin.hpp"
45 #include "vm/classcache.hpp"
46 #include "vm/exceptions.hpp"
47 #include "vm/field.hpp"
48 #include "vm/global.h"
49 #include "vm/globals.hpp"
50 #include "vm/linker.hpp"
51 #include "vm/loader.hpp"
52 #include "vm/method.hpp"
53 #include "vm/options.h"
54 #include "vm/package.hpp"
55 #include "vm/primitive.hpp"
56 #include "vm/resolve.hpp"
57 #include "vm/rt-timing.h"
58 #include "vm/string.hpp"
59 #include "vm/suck.hpp"
60 #include "vm/vm.hpp"
61
62
63 #if defined(ENABLE_JAVASE)
64 # include "vm/annotation.hpp"
65 # include "vm/stackmap.h"
66 #endif
67
68 #if defined(ENABLE_STATISTICS)
69 # include "vm/statistics.h"
70 #endif
71
72 #if defined(ENABLE_ZLIB)
73 # include "vm/zip.hpp"
74 #endif
75
76 #include "vm/jit/stubs.hpp"
77
78 #if defined(ENABLE_JVMTI)
79 # include "native/jvmti/cacaodbg.h"
80 #endif
81
82
83 /* global variables ***********************************************************/
84
85 static hashtable *hashtable_classloader;
86
87
88 /* loader_preinit **************************************************************
89
90    Initializes the classpath list and loads classes required for the
91    primitive table.
92
93    NOTE: Exceptions thrown during VM initialization are caught in the
94          exception functions themselves.
95
96 *******************************************************************************/
97  
98 void loader_preinit(void)
99 {
100         TRACESUBSYSTEMINITIALIZATION("loader_preinit");
101
102 #if defined(ENABLE_THREADS)
103         // Get current list of classpath entries.
104         SuckClasspath& suckclasspath = VM::get_current()->get_suckclasspath();
105
106         /* Initialize the monitor pointer for zip/jar file locking. */
107
108         for (SuckClasspath::iterator it = suckclasspath.begin(); it != suckclasspath.end(); it++) {
109                 list_classpath_entry* lce = *it;
110
111                 if (lce->type == CLASSPATH_ARCHIVE)
112                         lce->mutex = new Mutex();
113         }
114 #endif
115
116         /* initialize classloader hashtable, 10 entries should be enough */
117
118         hashtable_classloader = NEW(hashtable);
119         hashtable_create(hashtable_classloader, 10);
120
121         /* Load the most basic classes. */
122
123         assert(VM::get_current()->is_initializing() == true);
124
125         class_java_lang_Object     = load_class_bootstrap(utf_java_lang_Object);
126
127 #if defined(ENABLE_JAVASE)
128         class_java_lang_Cloneable  = load_class_bootstrap(utf_java_lang_Cloneable);
129         class_java_io_Serializable = load_class_bootstrap(utf_java_io_Serializable);
130 #endif
131 }
132
133
134 /* loader_init *****************************************************************
135
136    Loads all classes required in the VM.
137
138    NOTE: Exceptions thrown during VM initialization are caught in the
139          exception functions themselves.
140
141 *******************************************************************************/
142  
143 void loader_init(void)
144 {
145         TRACESUBSYSTEMINITIALIZATION("loader_init");
146
147         /* Load primitive-type wrapping classes. */
148
149         assert(VM::get_current()->is_initializing() == true);
150
151 #if defined(ENABLE_JAVASE)
152         class_java_lang_Void       = load_class_bootstrap(utf_java_lang_Void);
153 #endif
154
155         class_java_lang_Boolean    = load_class_bootstrap(utf_java_lang_Boolean);
156         class_java_lang_Byte       = load_class_bootstrap(utf_java_lang_Byte);
157         class_java_lang_Character  = load_class_bootstrap(utf_java_lang_Character);
158         class_java_lang_Short      = load_class_bootstrap(utf_java_lang_Short);
159         class_java_lang_Integer    = load_class_bootstrap(utf_java_lang_Integer);
160         class_java_lang_Long       = load_class_bootstrap(utf_java_lang_Long);
161         class_java_lang_Float      = load_class_bootstrap(utf_java_lang_Float);
162         class_java_lang_Double     = load_class_bootstrap(utf_java_lang_Double);
163
164         /* Load important system classes. */
165
166         class_java_lang_Class      = load_class_bootstrap(utf_java_lang_Class);
167         class_java_lang_String     = load_class_bootstrap(utf_java_lang_String);
168
169 #if defined(ENABLE_JAVASE)
170         class_java_lang_ClassLoader =
171                 load_class_bootstrap(utf_java_lang_ClassLoader);
172
173         class_java_lang_SecurityManager =
174                 load_class_bootstrap(utf_java_lang_SecurityManager);
175 #endif
176
177         class_java_lang_System     =
178                 load_class_bootstrap(utf_new_char("java/lang/System"));
179
180         class_java_lang_Thread     =
181                 load_class_bootstrap(utf_new_char("java/lang/Thread"));
182
183 #if defined(ENABLE_JAVASE)
184         class_java_lang_ThreadGroup =
185                 load_class_bootstrap(utf_java_lang_ThreadGroup);
186 #endif
187
188         class_java_lang_Throwable  = load_class_bootstrap(utf_java_lang_Throwable);
189
190 #if defined(WITH_JAVA_RUNTIME_LIBRARY_GNU_CLASSPATH)
191         class_java_lang_VMSystem   =
192                 load_class_bootstrap(utf_new_char("java/lang/VMSystem"));
193
194         class_java_lang_VMThread   =
195                 load_class_bootstrap(utf_new_char("java/lang/VMThread"));
196
197         class_java_lang_VMThrowable =
198                 load_class_bootstrap(utf_new_char("java/lang/VMThrowable"));
199 #endif
200
201         /* Important system exceptions. */
202
203         class_java_lang_Exception  = load_class_bootstrap(utf_java_lang_Exception);
204
205         class_java_lang_ClassNotFoundException =
206                 load_class_bootstrap(utf_java_lang_ClassNotFoundException);
207
208         class_java_lang_RuntimeException =
209                 load_class_bootstrap(utf_java_lang_RuntimeException);
210
211         /* Some classes which may be used often. */
212
213 #if defined(ENABLE_JAVASE)
214         class_java_lang_StackTraceElement      = load_class_bootstrap(utf_java_lang_StackTraceElement);
215
216         class_java_lang_reflect_Constructor    = load_class_bootstrap(utf_java_lang_reflect_Constructor);
217         class_java_lang_reflect_Field          = load_class_bootstrap(utf_java_lang_reflect_Field);
218         class_java_lang_reflect_Method         = load_class_bootstrap(utf_java_lang_reflect_Method);
219
220 # if defined(WITH_JAVA_RUNTIME_LIBRARY_GNU_CLASSPATH)
221         class_java_lang_reflect_VMConstructor  = load_class_bootstrap(utf_java_lang_reflect_VMConstructor);
222         class_java_lang_reflect_VMField        = load_class_bootstrap(utf_java_lang_reflect_VMField);
223         class_java_lang_reflect_VMMethod       = load_class_bootstrap(utf_java_lang_reflect_VMMethod);
224 # endif
225
226         class_java_security_PrivilegedAction   = load_class_bootstrap(utf_new_char("java/security/PrivilegedAction"));
227
228         class_java_util_HashMap                = load_class_bootstrap(utf_new_char("java/util/HashMap"));
229         class_java_util_Vector                 = load_class_bootstrap(utf_java_util_Vector);
230
231 # if defined(WITH_JAVA_RUNTIME_LIBRARY_OPENJDK)
232         class_sun_misc_Signal                  = load_class_bootstrap(utf_new_char("sun/misc/Signal"));
233         class_sun_reflect_MagicAccessorImpl    = load_class_bootstrap(utf_new_char("sun/reflect/MagicAccessorImpl"));
234 # endif
235
236         arrayclass_java_lang_Object =
237                 load_class_bootstrap(utf_new_char("[Ljava/lang/Object;"));
238
239 # if defined(ENABLE_ANNOTATIONS)
240         /* needed by annotation support */
241         class_sun_reflect_ConstantPool =
242                 load_class_bootstrap(utf_new_char("sun/reflect/ConstantPool"));
243
244 #  if defined(WITH_JAVA_RUNTIME_LIBRARY_GNU_CLASSPATH)
245         /* needed by GNU Classpaths annotation support */
246         class_sun_reflect_annotation_AnnotationParser =
247                 load_class_bootstrap(utf_new_char("sun/reflect/annotation/AnnotationParser"));
248 #  endif
249 # endif
250 #endif
251 }
252
253
254 /* loader_hashtable_classloader_add ********************************************
255
256    Adds an entry to the classloader hashtable.
257
258    REMEMBER: Also use this to register native loaders!
259
260 *******************************************************************************/
261
262 classloader_t *loader_hashtable_classloader_add(java_handle_t *cl)
263 {
264         hashtable_classloader_entry *cle;
265         u4   key;
266         u4   slot;
267
268         if (cl == NULL)
269                 return NULL;
270
271         hashtable_classloader->mutex->lock();
272
273         LLNI_CRITICAL_START;
274
275         /* key for entry is the hashcode of the classloader;
276            aligned to 16-byte boundaries */
277
278         key  = heap_hashcode(LLNI_DIRECT(cl)) >> 4;
279         slot = key & (hashtable_classloader->size - 1);
280         cle  = (hashtable_classloader_entry*) hashtable_classloader->ptr[slot];
281
282         /* search hashchain for existing entry */
283
284         while (cle) {
285                 if (cle->object == LLNI_DIRECT(cl))
286                         break;
287
288                 cle = cle->hashlink;
289         }
290
291         LLNI_CRITICAL_END;
292
293         /* if no classloader was found, we create a new entry here */
294
295         if (cle == NULL) {
296                 cle = NEW(hashtable_classloader_entry);
297
298 #if defined(ENABLE_GC_CACAO)
299                 /* register the classloader object with the GC */
300
301                 gc_reference_register(&(cle->object), GC_REFTYPE_CLASSLOADER);
302 #endif
303
304                 LLNI_CRITICAL_START;
305
306                 cle->object = LLNI_DIRECT(cl);
307
308                 LLNI_CRITICAL_END;
309
310 /*#define LOADER_DEBUG_CLASSLOADER*/
311 #ifdef LOADER_DEBUG_CLASSLOADER
312                 printf("CLASSLOADER: adding new classloader entry %p for %p: ", cle, cl);
313                 class_print(LLNI_vftbl_direct(cl)->class);
314                 printf("\n");
315                 fflush(stdout);
316 #endif
317
318                 /* insert entry into hashtable */
319
320                 cle->hashlink = (hashtable_classloader_entry*) hashtable_classloader->ptr[slot];
321                 hashtable_classloader->ptr[slot] = cle;
322
323                 /* update number of entries */
324
325                 hashtable_classloader->entries++;
326         }
327
328         hashtable_classloader->mutex->unlock();
329
330 #if defined(ENABLE_HANDLES)
331         return cle;
332 #else
333         return cl;
334 #endif
335 }
336
337
338 /* loader_hashtable_classloader_find *******************************************
339
340    Find an entry in the classloader hashtable.
341
342 *******************************************************************************/
343
344 classloader_t *loader_hashtable_classloader_find(java_handle_t *cl)
345 {
346         hashtable_classloader_entry *cle;
347         u4   key;
348         u4   slot;
349
350         if (cl == NULL)
351                 return NULL;
352
353         LLNI_CRITICAL_START;
354
355         /* key for entry is the hashcode of the classloader;
356            aligned to 16-byte boundaries */
357
358         key  = heap_hashcode(LLNI_DIRECT(cl)) >> 4;
359         slot = key & (hashtable_classloader->size - 1);
360         cle  = (hashtable_classloader_entry*) hashtable_classloader->ptr[slot];
361
362         /* search hashchain for existing entry */
363
364         while (cle) {
365                 if (cle->object == LLNI_DIRECT(cl))
366                         break;
367
368                 cle = cle->hashlink;
369         }
370
371 #ifdef LOADER_DEBUG_CLASSLOADER
372         if (cle == NULL) {
373                 printf("CLASSLOADER: unable to find classloader entry for %p: ", cl);
374                 class_print(LLNI_vftbl_direct(cl)->class);
375                 printf("\n");
376                 fflush(stdout);
377         }
378 #endif
379
380         LLNI_CRITICAL_END;
381
382 #if defined(ENABLE_HANDLES)
383         return cle;
384 #else
385         return cl;
386 #endif
387 }
388
389
390 /* loader_load_all_classes *****************************************************
391
392    Loads all classes specified in the BOOTCLASSPATH.
393
394 *******************************************************************************/
395
396 void loader_load_all_classes(void)
397 {
398 #if defined(ENABLE_ZLIB)
399         hashtable               *ht;
400         hashtable_zipfile_entry *htzfe;
401         utf                     *u;
402 #endif
403
404         // Get current list of classpath entries.
405         SuckClasspath& suckclasspath = VM::get_current()->get_suckclasspath();
406
407         for (SuckClasspath::iterator it = suckclasspath.begin(); it != suckclasspath.end(); it++) {
408                 list_classpath_entry* lce = *it;
409
410 #if defined(ENABLE_ZLIB)
411                 if (lce->type == CLASSPATH_ARCHIVE) {
412                         /* get the classes hashtable */
413
414                         ht = lce->htclasses;
415
416                         for (uint32_t slot = 0; slot < ht->size; slot++) {
417                                 htzfe = (hashtable_zipfile_entry *) ht->ptr[slot];
418
419                                 for (; htzfe; htzfe = htzfe->hashlink) {
420                                         u = htzfe->filename;
421
422                                         /* skip all entries in META-INF and .properties,
423                        .png files */
424
425                                         if (!strncmp(u->text, "META-INF", strlen("META-INF")) ||
426                                                 strstr(u->text, ".properties") ||
427                                                 strstr(u->text, ".png"))
428                                                 continue;
429
430                                         /* load class from bootstrap classloader */
431
432                                         if (!load_class_bootstrap(u)) {
433                                                 fprintf(stderr, "Error loading: ");
434                                                 utf_fprint_printable_ascii_classname(stderr, u);
435                                                 fprintf(stderr, "\n");
436
437 #if !defined(NDEBUG)
438                                                 /* print out exception and cause */
439
440                                                 exceptions_print_current_exception();
441 #endif
442                                         }
443                                 }
444                         }
445
446                 } else {
447 #endif
448 #if defined(ENABLE_ZLIB)
449                 }
450 #endif
451         }
452 }
453
454
455 /* loader_skip_attribute_body **************************************************
456
457    Skips an attribute the attribute_name_index has already been read.
458         
459    attribute_info {
460        u2 attribute_name_index;
461        u4 attribute_length;
462        u1 info[attribute_length];
463    }
464
465 *******************************************************************************/
466
467 bool loader_skip_attribute_body(classbuffer *cb)
468 {
469         u4 attribute_length;
470
471         if (!suck_check_classbuffer_size(cb, 4))
472                 return false;
473
474         attribute_length = suck_u4(cb);
475
476         if (!suck_check_classbuffer_size(cb, attribute_length))
477                 return false;
478
479         suck_skip_nbytes(cb, attribute_length);
480
481         return true;
482 }
483
484
485 /* load_constantpool ***********************************************************
486
487    Loads the constantpool of a class, the entries are transformed into
488    a simpler format by resolving references (a detailed overview of
489    the compact structures can be found in global.h).
490
491 *******************************************************************************/
492
493 static bool load_constantpool(classbuffer *cb, descriptor_pool *descpool)
494 {
495
496         /* The following structures are used to save information which cannot be 
497            processed during the first pass. After the complete constantpool has 
498            been traversed the references can be resolved. 
499            (only in specific order)                                                */
500         
501         /* CONSTANT_Class entries */
502         typedef struct forward_class {
503                 struct forward_class *next;
504                 u2 thisindex;
505                 u2 name_index;
506         } forward_class;
507
508         /* CONSTANT_String */
509         typedef struct forward_string {
510                 struct forward_string *next;
511                 u2 thisindex;
512                 u2 string_index;
513         } forward_string;
514
515         /* CONSTANT_NameAndType */
516         typedef struct forward_nameandtype {
517                 struct forward_nameandtype *next;
518                 u2 thisindex;
519                 u2 name_index;
520                 u2 sig_index;
521         } forward_nameandtype;
522
523         /* CONSTANT_Fieldref, CONSTANT_Methodref or CONSTANT_InterfaceMethodref */
524         typedef struct forward_fieldmethint {
525                 struct forward_fieldmethint *next;
526                 u2 thisindex;
527                 u1 tag;
528                 u2 class_index;
529                 u2 nameandtype_index;
530         } forward_fieldmethint;
531
532
533         classinfo *c;
534         u4 idx;
535
536         forward_class *forward_classes = NULL;
537         forward_string *forward_strings = NULL;
538         forward_nameandtype *forward_nameandtypes = NULL;
539         forward_fieldmethint *forward_fieldmethints = NULL;
540
541         forward_class *nfc;
542         forward_string *nfs;
543         forward_nameandtype *nfn;
544         forward_fieldmethint *nff;
545
546         u4 cpcount;
547         u1 *cptags;
548         void** cpinfos;
549
550         c = cb->clazz;
551
552         /* number of entries in the constant_pool table plus one */
553         if (!suck_check_classbuffer_size(cb, 2))
554                 return false;
555
556         cpcount = c->cpcount = suck_u2(cb);
557
558         /* allocate memory */
559         cptags  = c->cptags  = MNEW(u1, cpcount);
560         cpinfos = c->cpinfos = MNEW(void*, cpcount);
561
562         if (cpcount < 1) {
563                 exceptions_throw_classformaterror(c, "Illegal constant pool size");
564                 return false;
565         }
566         
567 #if defined(ENABLE_STATISTICS)
568         if (opt_stat)
569                 count_const_pool_len += (sizeof(u1) + sizeof(void*)) * cpcount;
570 #endif
571         
572         /* initialize constantpool */
573         for (idx = 0; idx < cpcount; idx++) {
574                 cptags[idx] = CONSTANT_UNUSED;
575                 cpinfos[idx] = NULL;
576         }
577
578                         
579         /******* first pass *******/
580         /* entries which cannot be resolved now are written into 
581            temporary structures and traversed again later        */
582                    
583         idx = 1;
584         while (idx < cpcount) {
585                 u4 t;
586
587                 /* get constant type */
588                 if (!suck_check_classbuffer_size(cb, 1))
589                         return false;
590
591                 t = suck_u1(cb);
592
593                 switch (t) {
594                 case CONSTANT_Class:
595 #warning Use list.
596                         nfc = (forward_class*) DumpMemory::allocate(sizeof(forward_class));
597
598                         nfc->next = forward_classes;
599                         forward_classes = nfc;
600
601                         nfc->thisindex = idx;
602                         /* reference to CONSTANT_NameAndType */
603                         if (!suck_check_classbuffer_size(cb, 2))
604                                 return false;
605
606                         nfc->name_index = suck_u2(cb);
607
608                         idx++;
609                         break;
610                         
611                 case CONSTANT_String:
612 #warning Use list.
613                         nfs = (forward_string*) DumpMemory::allocate(sizeof(forward_string));
614                                 
615                         nfs->next = forward_strings;
616                         forward_strings = nfs;
617                                 
618                         nfs->thisindex = idx;
619
620                         /* reference to CONSTANT_Utf8_info with string characters */
621                         if (!suck_check_classbuffer_size(cb, 2))
622                                 return false;
623
624                         nfs->string_index = suck_u2(cb);
625                                 
626                         idx++;
627                         break;
628
629                 case CONSTANT_NameAndType:
630 #warning Use list.
631                         nfn = (forward_nameandtype*) DumpMemory::allocate(sizeof(forward_nameandtype));
632                                 
633                         nfn->next = forward_nameandtypes;
634                         forward_nameandtypes = nfn;
635                                 
636                         nfn->thisindex = idx;
637
638                         if (!suck_check_classbuffer_size(cb, 2 + 2))
639                                 return false;
640
641                         /* reference to CONSTANT_Utf8_info containing simple name */
642                         nfn->name_index = suck_u2(cb);
643
644                         /* reference to CONSTANT_Utf8_info containing field or method
645                            descriptor */
646                         nfn->sig_index = suck_u2(cb);
647                                 
648                         idx++;
649                         break;
650
651                 case CONSTANT_Fieldref:
652                 case CONSTANT_Methodref:
653                 case CONSTANT_InterfaceMethodref:
654 #warning Use list.
655                         nff = (forward_fieldmethint*) DumpMemory::allocate(sizeof(forward_fieldmethint));
656                         
657                         nff->next = forward_fieldmethints;
658                         forward_fieldmethints = nff;
659
660                         nff->thisindex = idx;
661                         /* constant type */
662                         nff->tag = t;
663
664                         if (!suck_check_classbuffer_size(cb, 2 + 2))
665                                 return false;
666
667                         /* class or interface type that contains the declaration of the
668                            field or method */
669                         nff->class_index = suck_u2(cb);
670
671                         /* name and descriptor of the field or method */
672                         nff->nameandtype_index = suck_u2(cb);
673
674                         idx++;
675                         break;
676                                 
677                 case CONSTANT_Integer: {
678                         constant_integer *ci = NEW(constant_integer);
679
680 #if defined(ENABLE_STATISTICS)
681                         if (opt_stat)
682                                 count_const_pool_len += sizeof(constant_integer);
683 #endif
684
685                         if (!suck_check_classbuffer_size(cb, 4))
686                                 return false;
687
688                         ci->value = suck_s4(cb);
689                         cptags[idx] = CONSTANT_Integer;
690                         cpinfos[idx] = ci;
691
692                         idx++;
693                         break;
694                 }
695                                 
696                 case CONSTANT_Float: {
697                         constant_float *cf = NEW(constant_float);
698
699 #if defined(ENABLE_STATISTICS)
700                         if (opt_stat)
701                                 count_const_pool_len += sizeof(constant_float);
702 #endif
703
704                         if (!suck_check_classbuffer_size(cb, 4))
705                                 return false;
706
707                         cf->value = suck_float(cb);
708                         cptags[idx] = CONSTANT_Float;
709                         cpinfos[idx] = cf;
710
711                         idx++;
712                         break;
713                 }
714                                 
715                 case CONSTANT_Long: {
716                         constant_long *cl = NEW(constant_long);
717                                         
718 #if defined(ENABLE_STATISTICS)
719                         if (opt_stat)
720                                 count_const_pool_len += sizeof(constant_long);
721 #endif
722
723                         if (!suck_check_classbuffer_size(cb, 8))
724                                 return false;
725
726                         cl->value = suck_s8(cb);
727                         cptags[idx] = CONSTANT_Long;
728                         cpinfos[idx] = cl;
729                         idx += 2;
730                         if (idx > cpcount) {
731                                 exceptions_throw_classformaterror(c, "Invalid constant pool entry");
732                                 return false;
733                         }
734                         break;
735                 }
736                         
737                 case CONSTANT_Double: {
738                         constant_double *cd = NEW(constant_double);
739                                 
740 #if defined(ENABLE_STATISTICS)
741                         if (opt_stat)
742                                 count_const_pool_len += sizeof(constant_double);
743 #endif
744
745                         if (!suck_check_classbuffer_size(cb, 8))
746                                 return false;
747
748                         cd->value = suck_double(cb);
749                         cptags[idx] = CONSTANT_Double;
750                         cpinfos[idx] = cd;
751                         idx += 2;
752                         if (idx > cpcount) {
753                                 exceptions_throw_classformaterror(c, "Invalid constant pool entry");
754                                 return false;
755                         }
756                         break;
757                 }
758                                 
759                 case CONSTANT_Utf8: { 
760                         u4 length;
761
762                         /* number of bytes in the bytes array (not string-length) */
763                         if (!suck_check_classbuffer_size(cb, 2))
764                                 return false;
765
766                         length = suck_u2(cb);
767                         cptags[idx] = CONSTANT_Utf8;
768
769                         /* validate the string */
770                         if (!suck_check_classbuffer_size(cb, length))
771                                 return false;
772
773 #ifdef ENABLE_VERIFIER
774                         if (opt_verify &&
775                                 !is_valid_utf((char *) cb->pos, (char *) (cb->pos + length))) 
776                         {
777                                 exceptions_throw_classformaterror(c, "Invalid UTF-8 string");
778                                 return false;
779                         }
780 #endif /* ENABLE_VERIFIER */
781                         /* insert utf-string into the utf-symboltable */
782                         cpinfos[idx] = utf_new((char *) cb->pos, length);
783
784                         /* skip bytes of the string (buffer size check above) */
785                         suck_skip_nbytes(cb, length);
786                         idx++;
787                         break;
788                 }
789                                                                                 
790                 default:
791                         exceptions_throw_classformaterror(c, "Illegal constant pool type");
792                         return false;
793                 }  /* end switch */
794         } /* end while */
795
796
797         /* resolve entries in temporary structures */
798
799         while (forward_classes) {
800                 utf *name = (utf*) class_getconstant(c, forward_classes->name_index, CONSTANT_Utf8);
801                 if (!name)
802                         return false;
803
804 #ifdef ENABLE_VERIFIER
805                 if (opt_verify && !is_valid_name_utf(name)) {
806                         exceptions_throw_classformaterror(c, "Class reference with invalid name");
807                         return false;
808                 }
809 #endif /* ENABLE_VERIFIER */
810
811                 /* add all class references to the descriptor_pool */
812
813                 if (!descriptor_pool_add_class(descpool, name))
814                         return false;
815
816                 cptags[forward_classes->thisindex] = CONSTANT_Class;
817
818                 /* the classref is created later */
819                 cpinfos[forward_classes->thisindex] = name;
820
821                 nfc = forward_classes;
822                 forward_classes = forward_classes->next;
823         }
824
825         while (forward_strings) {
826                 utf *text = (utf*) class_getconstant(c, forward_strings->string_index, CONSTANT_Utf8);
827
828                 if (!text)
829                         return false;
830
831                 /* resolve utf-string */
832                 cptags[forward_strings->thisindex] = CONSTANT_String;
833                 cpinfos[forward_strings->thisindex] = text;
834                 
835                 nfs = forward_strings;
836                 forward_strings = forward_strings->next;
837         }
838
839         while (forward_nameandtypes) {
840                 constant_nameandtype *cn = NEW(constant_nameandtype);   
841
842 #if defined(ENABLE_STATISTICS)
843                 if (opt_stat)
844                         count_const_pool_len += sizeof(constant_nameandtype);
845 #endif
846
847                 /* resolve simple name and descriptor */
848                 cn->name = (utf*) class_getconstant(c,
849                                                                                         forward_nameandtypes->name_index,
850                                                                                         CONSTANT_Utf8);
851                 if (!cn->name)
852                         return false;
853
854                 cn->descriptor = (utf*) class_getconstant(c,
855                                                                                                   forward_nameandtypes->sig_index,
856                                                                                                   CONSTANT_Utf8);
857                 if (!cn->descriptor)
858                         return false;
859
860 #ifdef ENABLE_VERIFIER
861                 if (opt_verify) {
862                         /* check name */
863                         if (!is_valid_name_utf(cn->name)) {
864                                 exceptions_throw_classformaterror(c,
865                                                                                                   "Illegal Field name \"%s\"",
866                                                                                                   cn->name->text);
867
868                                 return false;
869                         }
870
871                         /* disallow referencing <clinit> among others */
872                         if (cn->name->text[0] == '<' && cn->name != utf_init) {
873                                 exceptions_throw_classformaterror(c, "Illegal reference to special method");
874                                 return false;
875                         }
876                 }
877 #endif /* ENABLE_VERIFIER */
878
879                 cptags[forward_nameandtypes->thisindex] = CONSTANT_NameAndType;
880                 cpinfos[forward_nameandtypes->thisindex] = cn;
881
882                 nfn = forward_nameandtypes;
883                 forward_nameandtypes = forward_nameandtypes->next;
884         }
885
886         while (forward_fieldmethints) {
887                 constant_nameandtype *nat;
888                 constant_FMIref *fmi = NEW(constant_FMIref);
889
890 #if defined(ENABLE_STATISTICS)
891                 if (opt_stat)
892                         count_const_pool_len += sizeof(constant_FMIref);
893 #endif
894                 /* resolve simple name and descriptor */
895
896                 nat = (constant_nameandtype*) class_getconstant(c,
897                                                                                                                 forward_fieldmethints->nameandtype_index,
898                                                                                                                 CONSTANT_NameAndType);
899
900                 if (!nat)
901                         return false;
902
903                 /* add all descriptors in {Field,Method}ref to the descriptor_pool */
904
905                 if (!descriptor_pool_add(descpool, nat->descriptor, NULL))
906                         return false;
907
908                 /* the classref is created later */
909
910                 fmi->p.index = forward_fieldmethints->class_index;
911                 fmi->name = nat->name;
912                 fmi->descriptor = nat->descriptor;
913
914                 cptags[forward_fieldmethints->thisindex] = forward_fieldmethints->tag;
915                 cpinfos[forward_fieldmethints->thisindex] = fmi;
916         
917                 nff = forward_fieldmethints;
918                 forward_fieldmethints = forward_fieldmethints->next;
919         }
920
921         /* everything was ok */
922
923         return true;
924 }
925
926
927 /* loader_load_attribute_signature *********************************************
928
929    Signature_attribute {
930        u2 attribute_name_index;
931            u4 atrribute_length;
932            u2 signature_index;
933    }
934
935 *******************************************************************************/
936
937 #if defined(ENABLE_JAVASE)
938 bool loader_load_attribute_signature(classbuffer *cb, utf **signature)
939 {
940         classinfo *c;
941         u4         attribute_length;
942         u2         signature_index;
943
944         /* get classinfo */
945
946         c = cb->clazz;
947
948         /* check remaining bytecode */
949
950         if (!suck_check_classbuffer_size(cb, 4 + 2))
951                 return false;
952
953         /* check attribute length */
954
955         attribute_length = suck_u4(cb);
956
957         if (attribute_length != 2) {
958                 exceptions_throw_classformaterror(c, "Wrong size for VALUE attribute");
959                 return false;
960         }
961
962         if (*signature != NULL) {
963                 exceptions_throw_classformaterror(c, "Multiple Signature attributes");
964                 return false;
965         }
966
967         /* get signature */
968
969         signature_index = suck_u2(cb);
970
971         *signature = (utf*) class_getconstant(c, signature_index, CONSTANT_Utf8);
972
973         if (*signature == NULL)
974                 return false;
975
976         return true;
977 }
978 #endif /* defined(ENABLE_JAVASE) */
979
980
981 /* load_class_from_sysloader ***************************************************
982
983    Load the class with the given name using the system class loader
984
985    IN:
986        name.............the classname
987
988    RETURN VALUE:
989        the loaded class, or
990            NULL if an exception has been thrown
991
992 *******************************************************************************/
993
994 classinfo *load_class_from_sysloader(utf *name)
995 {
996         methodinfo    *m;
997         java_handle_t *clo;
998         classloader_t *cl;
999         classinfo     *c;
1000
1001         assert(class_java_lang_Object);
1002         assert(class_java_lang_ClassLoader);
1003         assert(class_java_lang_ClassLoader->state & CLASS_LINKED);
1004         
1005         m = class_resolveclassmethod(class_java_lang_ClassLoader,
1006                                                                  utf_getSystemClassLoader,
1007                                                                  utf_void__java_lang_ClassLoader,
1008                                                                  class_java_lang_Object,
1009                                                                  false);
1010
1011         if (!m)
1012                 return false;
1013
1014         clo = vm_call_method(m, NULL);
1015
1016         if (!clo)
1017                 return false;
1018
1019         cl = loader_hashtable_classloader_add(clo);
1020
1021         c = load_class_from_classloader(name, cl);
1022
1023         return c;
1024 }
1025
1026
1027 /* load_class_from_classloader *************************************************
1028
1029    Load the class with the given name using the given user-defined class loader.
1030
1031    IN:
1032        name.............the classname
1033            cl...............user-defined class loader
1034            
1035    RETURN VALUE:
1036        the loaded class, or
1037            NULL if an exception has been thrown
1038
1039 *******************************************************************************/
1040
1041 classinfo *load_class_from_classloader(utf *name, classloader_t *cl)
1042 {
1043         java_handle_t *o;
1044         classinfo     *c;
1045         classinfo     *tmpc;
1046         java_handle_t *string;
1047 #if defined(ENABLE_RT_TIMING)
1048         struct timespec time_start, time_lookup, time_prepare, time_java, 
1049                                         time_cache;
1050 #endif
1051
1052         RT_TIMING_GET_TIME(time_start);
1053
1054         assert(name);
1055
1056         /* lookup if this class has already been loaded */
1057
1058         c = classcache_lookup(cl, name);
1059
1060         RT_TIMING_GET_TIME(time_lookup);
1061         RT_TIMING_TIME_DIFF(time_start,time_lookup,RT_TIMING_LOAD_CL_LOOKUP);
1062
1063         if (c != NULL)
1064                 return c;
1065
1066         /* if other class loader than bootstrap, call it */
1067
1068         if (cl != NULL) {
1069                 methodinfo *lc;
1070                 char       *text;
1071                 s4          namelen;
1072
1073                 text = name->text;
1074                 namelen = name->blength;
1075
1076                 /* handle array classes */
1077                 if (text[0] == '[') {
1078                         classinfo *comp;
1079                         utf       *u;
1080
1081                         switch (text[1]) {
1082                         case 'L':
1083                                 /* check for cases like `[L;' or `[L[I;' or `[Ljava.lang.Object' */
1084                                 if (namelen < 4 || text[2] == '[' || text[namelen - 1] != ';') {
1085                                         exceptions_throw_classnotfoundexception(name);
1086                                         return false;
1087                                 }
1088
1089                                 u = utf_new(text + 2, namelen - 3);
1090
1091                                 if (!(comp = load_class_from_classloader(u, cl)))
1092                                         return false;
1093
1094                                 /* create the array class */
1095
1096                                 c = class_array_of(comp, false);
1097
1098                                 tmpc = classcache_store(cl, c, true);
1099
1100                                 if (tmpc == NULL) {
1101                                         /* exception, free the loaded class */
1102                                         c->state &= ~CLASS_LOADING;
1103                                         class_free(c);
1104                                 }
1105
1106                                 return tmpc;
1107
1108                         case '[':
1109                                 /* load the component class */
1110
1111                                 u = utf_new(text + 1, namelen - 1);
1112
1113                                 if (!(comp = load_class_from_classloader(u, cl)))
1114                                         return false;
1115
1116                                 /* create the array class */
1117
1118                                 c = class_array_of(comp, false);
1119
1120                                 tmpc = classcache_store(cl, c, true);
1121
1122                                 if (tmpc == NULL) {
1123                                         /* exception, free the loaded class */
1124                                         c->state &= ~CLASS_LOADING;
1125                                         class_free(c);
1126                                 }
1127
1128                                 return tmpc;
1129
1130                         default:
1131                                 /* primitive array classes are loaded by the bootstrap loader */
1132
1133                                 c = load_class_bootstrap(name);
1134
1135                                 return c;
1136                         }
1137                 }
1138
1139                 LLNI_class_get(cl, c);
1140
1141 #if defined(WITH_JAVA_RUNTIME_LIBRARY_OPENJDK)
1142                 /* OpenJDK uses this internal function because it's
1143                    synchronized. */
1144
1145                 lc = class_resolveclassmethod(c,
1146                                                                           utf_loadClassInternal,
1147                                                                           utf_java_lang_String__java_lang_Class,
1148                                                                           NULL,
1149                                                                           true);
1150 #else
1151                 lc = class_resolveclassmethod(c,
1152                                                                           utf_loadClass,
1153                                                                           utf_java_lang_String__java_lang_Class,
1154                                                                           NULL,
1155                                                                           true);
1156 #endif
1157
1158                 if (lc == NULL)
1159                         return false; /* exception */
1160
1161                 /* move return value into `o' and cast it afterwards to a classinfo* */
1162
1163                 string = javastring_new_slash_to_dot(name);
1164
1165                 RT_TIMING_GET_TIME(time_prepare);
1166
1167                 o = vm_call_method(lc, (java_handle_t *) cl, string);
1168
1169                 RT_TIMING_GET_TIME(time_java);
1170
1171                 c = LLNI_classinfo_unwrap(o);
1172
1173                 if (c != NULL) {
1174                         /* Store this class in the loaded class cache. If another
1175                            class with the same (initloader,name) pair has been
1176                            stored earlier it will be returned by classcache_store
1177                            In this case classcache_store may not free the class
1178                            because it has already been exposed to Java code which
1179                            may have kept references to that class. */
1180
1181                     tmpc = classcache_store(cl, c, false);
1182
1183                         if (tmpc == NULL) {
1184                                 /* exception, free the loaded class */
1185                                 c->state &= ~CLASS_LOADING;
1186                                 class_free(c);
1187                         }
1188
1189                         c = tmpc;
1190                 }
1191
1192                 RT_TIMING_GET_TIME(time_cache);
1193
1194                 RT_TIMING_TIME_DIFF(time_lookup , time_prepare, RT_TIMING_LOAD_CL_PREPARE);
1195                 RT_TIMING_TIME_DIFF(time_prepare, time_java   , RT_TIMING_LOAD_CL_JAVA);
1196                 RT_TIMING_TIME_DIFF(time_java   , time_cache  , RT_TIMING_LOAD_CL_CACHE);
1197
1198                 /* SUN compatible -verbose:class output */
1199
1200                 if (opt_verboseclass && (c != NULL) && (c->classloader == cl)) {
1201                         printf("[Loaded ");
1202                         utf_display_printable_ascii_classname(name);
1203                         printf("]\n");
1204                 }
1205
1206 #if defined(ENABLE_JVMTI)
1207                 /* fire Class Load JVMTI event */
1208                 if (jvmti) jvmti_ClassLoadPrepare(false, c);
1209 #endif
1210
1211
1212                 return c;
1213         } 
1214
1215         c = load_class_bootstrap(name);
1216
1217         return c;
1218 }
1219
1220
1221 /* load_class_bootstrap ********************************************************
1222         
1223    Load the class with the given name using the bootstrap class loader.
1224
1225    IN:
1226        name.............the classname
1227
1228    RETURN VALUE:
1229        loaded classinfo, or
1230            NULL if an exception has been thrown
1231
1232    SYNCHRONIZATION:
1233        load_class_bootstrap is synchronized. It can be treated as an
1234            atomic operation.
1235
1236 *******************************************************************************/
1237
1238 classinfo *load_class_bootstrap(utf *name)
1239 {
1240         classbuffer *cb;
1241         classinfo   *c;
1242         classinfo   *r;
1243 #if defined(ENABLE_RT_TIMING)
1244         struct timespec time_start, time_lookup, time_array, time_suck, 
1245                                         time_load, time_cache;
1246 #endif
1247
1248         RT_TIMING_GET_TIME(time_start);
1249
1250         /* for debugging */
1251
1252         assert(name);
1253
1254         /* lookup if this class has already been loaded */
1255
1256         r = classcache_lookup(NULL, name);
1257
1258         if (r != NULL) {
1259                 RT_TIMING_GET_TIME(time_lookup);
1260                 RT_TIMING_TIME_DIFF(time_start,time_lookup,RT_TIMING_LOAD_BOOT_LOOKUP);
1261                 
1262                 return r;
1263         }
1264
1265         RT_TIMING_GET_TIME(time_lookup);
1266         RT_TIMING_TIME_DIFF(time_start,time_lookup,RT_TIMING_LOAD_BOOT_LOOKUP);
1267                 
1268         /* create the classinfo */
1269
1270         c = class_create_classinfo(name);
1271
1272         /* handle array classes */
1273
1274         if (name->text[0] == '[') {
1275                 c = load_newly_created_array(c, NULL);
1276
1277                 if (c == NULL)
1278                         return NULL;
1279
1280                 assert(c->state & CLASS_LOADED);
1281
1282                 RT_TIMING_GET_TIME(time_array);
1283                 RT_TIMING_TIME_DIFF(time_start,time_array,RT_TIMING_LOAD_BOOT_ARRAY);
1284                 
1285                 return c;
1286         }
1287
1288 #if defined(ENABLE_STATISTICS)
1289         /* measure time */
1290
1291         if (opt_getcompilingtime)
1292                 compilingtime_stop();
1293
1294         if (opt_getloadingtime)
1295                 loadingtime_start();
1296 #endif
1297
1298         /* load classdata, throw exception on error */
1299
1300         cb = suck_start(c);
1301
1302         if (cb == NULL) {
1303                 exceptions_throw_classnotfoundexception(name);
1304                 return NULL;
1305         }
1306
1307         RT_TIMING_GET_TIME(time_suck);
1308         
1309         /* load the class from the buffer */
1310
1311         r = load_class_from_classbuffer(cb);
1312
1313         RT_TIMING_GET_TIME(time_load);
1314         
1315         if (r == NULL) {
1316                 /* the class could not be loaded, free the classinfo struct */
1317
1318                 class_free(c);
1319         }
1320         else {
1321                 /* Store this class in the loaded class cache this step also
1322                    checks the loading constraints. If the class has been
1323                    loaded before, the earlier loaded class is returned. */
1324
1325                 classinfo *res = classcache_store(NULL, c, true);
1326
1327                 if (res == NULL) {
1328                         /* exception */
1329                         class_free(c);
1330                 }
1331                 else {
1332                         // Add the package name to the boot packages.
1333                         Package::add(c->packagename);
1334                 }
1335
1336                 r = res;
1337         }
1338
1339         RT_TIMING_GET_TIME(time_cache);
1340         
1341         /* SUN compatible -verbose:class output */
1342
1343         if (opt_verboseclass && r) {
1344                 printf("[Loaded ");
1345                 utf_display_printable_ascii_classname(name);
1346                 printf(" from %s]\n", cb->path);
1347         }
1348
1349         /* free memory */
1350
1351         suck_stop(cb);
1352
1353 #if defined(ENABLE_STATISTICS)
1354         /* measure time */
1355
1356         if (opt_getloadingtime)
1357                 loadingtime_stop();
1358
1359         if (opt_getcompilingtime)
1360                 compilingtime_start();
1361 #endif
1362
1363         RT_TIMING_TIME_DIFF(time_lookup, time_suck , RT_TIMING_LOAD_BOOT_SUCK);
1364         RT_TIMING_TIME_DIFF(time_suck  , time_load , RT_TIMING_LOAD_BOOT_LOAD);
1365         RT_TIMING_TIME_DIFF(time_load  , time_cache, RT_TIMING_LOAD_BOOT_CACHE);
1366         RT_TIMING_TIME_DIFF(time_lookup, time_cache, RT_TIMING_LOAD_BOOT_TOTAL);
1367
1368         return r;
1369 }
1370
1371
1372 /* load_class_from_classbuffer_intern ******************************************
1373         
1374    Loads a class from a classbuffer into a given classinfo structure.
1375    Super-classes are also loaded at this point and some verfication
1376    checks are done.
1377
1378    SYNCHRONIZATION:
1379        This function is NOT synchronized!
1380    
1381 *******************************************************************************/
1382
1383 static bool load_class_from_classbuffer_intern(classbuffer *cb)
1384 {
1385         classinfo          *c;
1386         classinfo          *tc;
1387         utf                *name;
1388         utf                *supername;
1389         utf               **interfacesnames;
1390         utf                *u;
1391         constant_classref  *cr;
1392         int16_t             index;
1393
1394         u4 ma, mi;
1395         descriptor_pool *descpool;
1396 #if defined(ENABLE_STATISTICS)
1397         u4 classrefsize;
1398         u4 descsize;
1399 #endif
1400 #if defined(ENABLE_RT_TIMING)
1401         struct timespec time_start, time_checks, time_ndpool, time_cpool,
1402                                         time_setup, time_fields, time_methods, time_classrefs,
1403                                         time_descs,     time_setrefs, time_parsefds, time_parsemds,
1404                                         time_parsecpool, time_verify, time_attrs;
1405 #endif
1406
1407         // Create new dump memory area.
1408         DumpMemoryArea dma;
1409
1410         RT_TIMING_GET_TIME(time_start);
1411
1412         /* Get the classbuffer's class. */
1413
1414         c = cb->clazz;
1415
1416         if (!suck_check_classbuffer_size(cb, 4 + 2 + 2))
1417                 return false;
1418
1419         /* check signature */
1420
1421         if (suck_u4(cb) != MAGIC) {
1422                 exceptions_throw_classformaterror(c, "Bad magic number");
1423                 return false;
1424         }
1425
1426         /* check version */
1427
1428         mi = suck_u2(cb);
1429         ma = suck_u2(cb);
1430
1431         if (!(ma < MAJOR_VERSION || (ma == MAJOR_VERSION && mi <= MINOR_VERSION))) {
1432                 exceptions_throw_unsupportedclassversionerror(c, ma, mi);
1433                 return false;
1434         }
1435
1436         RT_TIMING_GET_TIME(time_checks);
1437
1438         /* create a new descriptor pool */
1439
1440         descpool = descriptor_pool_new(c);
1441
1442         RT_TIMING_GET_TIME(time_ndpool);
1443
1444         /* load the constant pool */
1445
1446         if (!load_constantpool(cb, descpool))
1447                 return false;
1448
1449         RT_TIMING_GET_TIME(time_cpool);
1450
1451         /* ACC flags */
1452
1453         if (!suck_check_classbuffer_size(cb, 2))
1454                 return false;
1455
1456         /* We OR the flags here, as we set already some flags in
1457            class_create_classinfo. */
1458
1459         c->flags |= suck_u2(cb);
1460
1461         /* check ACC flags consistency */
1462
1463         if (c->flags & ACC_INTERFACE) {
1464                 if (!(c->flags & ACC_ABSTRACT)) {
1465                         /* We work around this because interfaces in JDK 1.1 are
1466                          * not declared abstract. */
1467
1468                         c->flags |= ACC_ABSTRACT;
1469                 }
1470
1471                 if (c->flags & ACC_FINAL) {
1472                         exceptions_throw_classformaterror(c,
1473                                                                                           "Illegal class modifiers: 0x%X",
1474                                                                                           c->flags);
1475                         return false;
1476                 }
1477
1478                 if (c->flags & ACC_SUPER) {
1479                         c->flags &= ~ACC_SUPER; /* kjc seems to set this on interfaces */
1480                 }
1481         }
1482
1483         if ((c->flags & (ACC_ABSTRACT | ACC_FINAL)) == (ACC_ABSTRACT | ACC_FINAL)) {
1484                 exceptions_throw_classformaterror(c,
1485                                                                                   "Illegal class modifiers: 0x%X",
1486                                                                                   c->flags);
1487                 return false;
1488         }
1489
1490         if (!suck_check_classbuffer_size(cb, 2 + 2))
1491                 return false;
1492
1493         /* This class. */
1494
1495         index = suck_u2(cb);
1496
1497         name = (utf *) class_getconstant(c, index, CONSTANT_Class);
1498
1499         if (name == NULL)
1500                 return false;
1501
1502         if (c->name == utf_not_named_yet) {
1503                 /* we finally have a name for this class */
1504                 c->name = name;
1505                 class_set_packagename(c);
1506         }
1507         else if (name != c->name) {
1508                 exceptions_throw_noclassdeffounderror_wrong_name(c, name);
1509                 return false;
1510         }
1511
1512         /* Retrieve superclass. */
1513
1514         c->super = NULL;
1515
1516         index = suck_u2(cb);
1517
1518         if (index == 0) {
1519                 supername = NULL;
1520
1521                 /* This is only allowed for java.lang.Object. */
1522
1523                 if (c->name != utf_java_lang_Object) {
1524                         exceptions_throw_classformaterror(c, "Bad superclass index");
1525                         return false;
1526                 }
1527         }
1528         else {
1529                 supername = (utf *) class_getconstant(c, index, CONSTANT_Class);
1530
1531                 if (supername == NULL)
1532                         return false;
1533
1534                 /* java.lang.Object may not have a super class. */
1535
1536                 if (c->name == utf_java_lang_Object) {
1537                         exceptions_throw_classformaterror(NULL, "java.lang.Object with superclass");
1538                         return false;
1539                 }
1540
1541                 /* Detect circularity. */
1542
1543                 if (supername == c->name) {
1544                         exceptions_throw_classcircularityerror(c);
1545                         return false;
1546                 }
1547
1548                 /* Interfaces must have java.lang.Object as super class. */
1549
1550                 if ((c->flags & ACC_INTERFACE) && (supername != utf_java_lang_Object)) {
1551                         exceptions_throw_classformaterror(c, "Interfaces must have java.lang.Object as superclass");
1552                         return false;
1553                 }
1554         }
1555
1556         /* Parse the super interfaces. */
1557
1558         if (!suck_check_classbuffer_size(cb, 2))
1559                 return false;
1560
1561         c->interfacescount = suck_u2(cb);
1562
1563         if (!suck_check_classbuffer_size(cb, 2 * c->interfacescount))
1564                 return false;
1565
1566         c->interfaces = MNEW(classinfo*, c->interfacescount);
1567
1568         /* Get the names of the super interfaces. */
1569
1570         interfacesnames = (utf**) DumpMemory::allocate(sizeof(utf*) * c->interfacescount);
1571
1572         for (int32_t i = 0; i < c->interfacescount; i++) {
1573                 index = suck_u2(cb);
1574
1575                 u = (utf *) class_getconstant(c, index, CONSTANT_Class);
1576
1577                 if (u == NULL)
1578                         return false;
1579
1580                 interfacesnames[i] = u;
1581         }
1582
1583         RT_TIMING_GET_TIME(time_setup);
1584
1585         /* Parse fields. */
1586
1587         if (!suck_check_classbuffer_size(cb, 2))
1588                 return false;
1589
1590         c->fieldscount = suck_u2(cb);
1591         c->fields      = MNEW(fieldinfo, c->fieldscount);
1592
1593         MZERO(c->fields, fieldinfo, c->fieldscount);
1594
1595         for (int32_t i = 0; i < c->fieldscount; i++) {
1596                 if (!field_load(cb, &(c->fields[i]), descpool))
1597                         return false;
1598         }
1599
1600         RT_TIMING_GET_TIME(time_fields);
1601
1602         /* Parse methods. */
1603
1604         if (!suck_check_classbuffer_size(cb, 2))
1605                 return false;
1606
1607         c->methodscount = suck_u2(cb);
1608         c->methods      = MNEW(methodinfo, c->methodscount);
1609
1610         MZERO(c->methods, methodinfo, c->methodscount);
1611         
1612         for (int32_t i = 0; i < c->methodscount; i++) {
1613                 if (!method_load(cb, &(c->methods[i]), descpool))
1614                         return false;
1615         }
1616
1617         RT_TIMING_GET_TIME(time_methods);
1618
1619         /* create the class reference table */
1620
1621         c->classrefs =
1622                 descriptor_pool_create_classrefs(descpool, &(c->classrefcount));
1623
1624         RT_TIMING_GET_TIME(time_classrefs);
1625
1626         /* allocate space for the parsed descriptors */
1627
1628         descriptor_pool_alloc_parsed_descriptors(descpool);
1629         c->parseddescs = (u1*) descriptor_pool_get_parsed_descriptors(descpool, &(c->parseddescsize));
1630
1631 #if defined(ENABLE_STATISTICS)
1632         if (opt_stat) {
1633                 descriptor_pool_get_sizes(descpool, &classrefsize, &descsize);
1634                 count_classref_len += classrefsize;
1635                 count_parsed_desc_len += descsize;
1636         }
1637 #endif
1638
1639         RT_TIMING_GET_TIME(time_descs);
1640
1641         /* put the classrefs in the constant pool */
1642
1643         for (int32_t i = 0; i < c->cpcount; i++) {
1644                 if (c->cptags[i] == CONSTANT_Class) {
1645                         utf *name = (utf *) c->cpinfos[i];
1646                         c->cpinfos[i] = descriptor_pool_lookup_classref(descpool, name);
1647                 }
1648         }
1649
1650         /* Resolve the super class. */
1651
1652         if (supername != NULL) {
1653                 cr = descriptor_pool_lookup_classref(descpool, supername);
1654
1655                 if (cr == NULL)
1656                         return false;
1657
1658                 /* XXX This should be done better. */
1659                 tc = resolve_classref_or_classinfo_eager(CLASSREF_OR_CLASSINFO(cr), false);
1660
1661                 if (tc == NULL) {
1662                         resolve_handle_pending_exception(true);
1663                         return false;
1664                 }
1665
1666                 /* Interfaces are not allowed as super classes. */
1667
1668                 if (tc->flags & ACC_INTERFACE) {
1669                         exceptions_throw_incompatibleclasschangeerror(c, "class %s has interface %s as super class");
1670                         return false;
1671                 }
1672
1673                 /* Don't allow extending final classes */
1674
1675                 if (tc->flags & ACC_FINAL) {
1676                         exceptions_throw_verifyerror(NULL,
1677                                                                                  "Cannot inherit from final class");
1678                         return false;
1679                 }
1680
1681                 /* Store the super class. */
1682
1683                 c->super = tc;
1684         }
1685
1686         /* Resolve the super interfaces. */
1687
1688         for (int32_t i = 0; i < c->interfacescount; i++) {
1689                 u  = interfacesnames[i];
1690                 cr = descriptor_pool_lookup_classref(descpool, u);
1691
1692                 if (cr == NULL)
1693                         return false;
1694
1695                 /* XXX This should be done better. */
1696                 tc = resolve_classref_or_classinfo_eager(CLASSREF_OR_CLASSINFO(cr), false);
1697
1698                 if (tc == NULL) {
1699                         resolve_handle_pending_exception(true);
1700                         return false;
1701                 }
1702
1703                 /* Detect circularity. */
1704
1705                 if (tc == c) {
1706                         exceptions_throw_classcircularityerror(c);
1707                         return false;
1708                 }
1709
1710                 if (!(tc->flags & ACC_INTERFACE)) {
1711                         exceptions_throw_incompatibleclasschangeerror(tc,
1712                                                                                                                   "Implementing class");
1713                         return false;
1714                 }
1715
1716                 /* Store the super interface. */
1717
1718                 c->interfaces[i] = tc;
1719         }
1720
1721         RT_TIMING_GET_TIME(time_setrefs);
1722
1723         /* Parse the field descriptors. */
1724
1725         for (int32_t i = 0; i < c->fieldscount; i++) {
1726                 c->fields[i].parseddesc =
1727                         descriptor_pool_parse_field_descriptor(descpool,
1728                                                                                                    c->fields[i].descriptor);
1729                 if (!c->fields[i].parseddesc)
1730                         return false;
1731         }
1732
1733         RT_TIMING_GET_TIME(time_parsefds);
1734
1735         /* parse method descriptors */
1736
1737         for (int32_t i = 0; i < c->methodscount; i++) {
1738                 methodinfo *m = &c->methods[i];
1739                 m->parseddesc =
1740                         descriptor_pool_parse_method_descriptor(descpool, m->descriptor,
1741                                                                                                         m->flags, class_get_self_classref(m->clazz));
1742                 if (!m->parseddesc)
1743                         return false;
1744
1745                 for (int32_t j = 0; j < m->rawexceptiontablelength; j++) {
1746                         if (!m->rawexceptiontable[j].catchtype.any)
1747                                 continue;
1748
1749                         if ((m->rawexceptiontable[j].catchtype.ref =
1750                                  descriptor_pool_lookup_classref(descpool,
1751                                                 (utf *) m->rawexceptiontable[j].catchtype.any)) == NULL)
1752                                 return false;
1753                 }
1754
1755                 for (int32_t j = 0; j < m->thrownexceptionscount; j++) {
1756                         if (!m->thrownexceptions[j].any)
1757                                 continue;
1758
1759                         if ((m->thrownexceptions[j].ref = descriptor_pool_lookup_classref(descpool,
1760                                                 (utf *) m->thrownexceptions[j].any)) == NULL)
1761                                 return false;
1762                 }
1763         }
1764
1765         RT_TIMING_GET_TIME(time_parsemds);
1766
1767         /* parse the loaded descriptors */
1768
1769         for (int32_t i = 0; i < c->cpcount; i++) {
1770                 constant_FMIref *fmi;
1771                 s4               index;
1772
1773                 switch (c->cptags[i]) {
1774                 case CONSTANT_Fieldref:
1775                         fmi = (constant_FMIref *) c->cpinfos[i];
1776                         fmi->parseddesc.fd =
1777                                 descriptor_pool_parse_field_descriptor(descpool,
1778                                                                                                            fmi->descriptor);
1779                         if (!fmi->parseddesc.fd)
1780                                 return false;
1781
1782                         index = fmi->p.index;
1783                         fmi->p.classref =
1784                                 (constant_classref *) class_getconstant(c, index,
1785                                                                                                                 CONSTANT_Class);
1786                         if (!fmi->p.classref)
1787                                 return false;
1788                         break;
1789                 case CONSTANT_Methodref:
1790                 case CONSTANT_InterfaceMethodref:
1791                         fmi = (constant_FMIref *) c->cpinfos[i];
1792                         index = fmi->p.index;
1793                         fmi->p.classref =
1794                                 (constant_classref *) class_getconstant(c, index,
1795                                                                                                                 CONSTANT_Class);
1796                         if (!fmi->p.classref)
1797                                 return false;
1798                         fmi->parseddesc.md =
1799                                 descriptor_pool_parse_method_descriptor(descpool,
1800                                                                                                                 fmi->descriptor,
1801                                                                                                                 ACC_UNDEF,
1802                                                                                                                 fmi->p.classref);
1803                         if (!fmi->parseddesc.md)
1804                                 return false;
1805                         break;
1806                 }
1807         }
1808
1809         RT_TIMING_GET_TIME(time_parsecpool);
1810
1811 #ifdef ENABLE_VERIFIER
1812         /* Check if all fields and methods can be uniquely
1813          * identified by (name,descriptor). */
1814
1815         if (opt_verify) {
1816                 /* We use a hash table here to avoid making the
1817                  * average case quadratic in # of methods, fields.
1818                  */
1819                 static int shift = 0;
1820                 u2 *hashtab;
1821                 u2 *next; /* for chaining colliding hash entries */
1822                 int32_t len;
1823                 int32_t hashlen;
1824                 u2 index;
1825                 u2 old;
1826
1827                 /* Allocate hashtable */
1828                 len = c->methodscount;
1829                 if (len < c->fieldscount) len = c->fieldscount;
1830                 hashlen = 5 * len;
1831                 hashtab = MNEW(u2,(hashlen + len));
1832                 next = hashtab + hashlen;
1833
1834                 /* Determine bitshift (to get good hash values) */
1835                 if (!shift) {
1836                         len = sizeof(utf);
1837                         while (len) {
1838                                 len >>= 1;
1839                                 shift++;
1840                         }
1841                 }
1842
1843                 /* Check fields */
1844                 memset(hashtab, 0, sizeof(u2) * (hashlen + len));
1845
1846                 for (int32_t i = 0; i < c->fieldscount; ++i) {
1847                         fieldinfo *fi = c->fields + i;
1848
1849                         /* It's ok if we lose bits here */
1850                         index = ((((size_t) fi->name) +
1851                                           ((size_t) fi->descriptor)) >> shift) % hashlen;
1852
1853                         if ((old = hashtab[index])) {
1854                                 old--;
1855                                 next[i] = old;
1856                                 do {
1857                                         if (c->fields[old].name == fi->name &&
1858                                                 c->fields[old].descriptor == fi->descriptor) {
1859                                                 exceptions_throw_classformaterror(c, "Repetitive field name/signature");
1860                                                 return false;
1861                                         }
1862                                 } while ((old = next[old]));
1863                         }
1864                         hashtab[index] = i + 1;
1865                 }
1866
1867                 /* Check methods */
1868                 memset(hashtab, 0, sizeof(u2) * (hashlen + hashlen/5));
1869
1870                 for (int32_t i = 0; i < c->methodscount; ++i) {
1871                         methodinfo *mi = c->methods + i;
1872
1873                         /* It's ok if we lose bits here */
1874                         index = ((((size_t) mi->name) +
1875                                           ((size_t) mi->descriptor)) >> shift) % hashlen;
1876
1877                         if ((old = hashtab[index])) {
1878                                 old--;
1879                                 next[i] = old;
1880                                 do {
1881                                         if (c->methods[old].name == mi->name &&
1882                                                 c->methods[old].descriptor == mi->descriptor) {
1883                                                 exceptions_throw_classformaterror(c, "Repetitive method name/signature");
1884                                                 return false;
1885                                         }
1886                                 } while ((old = next[old]));
1887                         }
1888                         hashtab[index] = i + 1;
1889                 }
1890
1891                 MFREE(hashtab, u2, (hashlen + len));
1892         }
1893 #endif /* ENABLE_VERIFIER */
1894
1895         RT_TIMING_GET_TIME(time_verify);
1896
1897 #if defined(ENABLE_STATISTICS)
1898         if (opt_stat) {
1899                 size_classinfo  += sizeof(classinfo*) * c->interfacescount;
1900                 size_fieldinfo  += sizeof(fieldinfo)  * c->fieldscount;
1901                 size_methodinfo += sizeof(methodinfo) * c->methodscount;
1902         }
1903 #endif
1904
1905         /* load attribute structures */
1906
1907         if (!class_load_attributes(cb))
1908                 return false;
1909
1910         /* Pre Java 1.5 version don't check this. This implementation is
1911            like Java 1.5 do it: for class file version 45.3 we don't check
1912            it, older versions are checked. */
1913
1914         if (((ma == 45) && (mi > 3)) || (ma > 45)) {
1915                 /* check if all data has been read */
1916                 s4 classdata_left = ((cb->data + cb->size) - cb->pos);
1917
1918                 if (classdata_left > 0) {
1919                         exceptions_throw_classformaterror(c, "Extra bytes at the end of class file");
1920                         return false;
1921                 }
1922         }
1923
1924         RT_TIMING_GET_TIME(time_attrs);
1925
1926         RT_TIMING_TIME_DIFF(time_start     , time_checks    , RT_TIMING_LOAD_CHECKS);
1927         RT_TIMING_TIME_DIFF(time_checks    , time_ndpool    , RT_TIMING_LOAD_NDPOOL);
1928         RT_TIMING_TIME_DIFF(time_ndpool    , time_cpool     , RT_TIMING_LOAD_CPOOL);
1929         RT_TIMING_TIME_DIFF(time_cpool     , time_setup     , RT_TIMING_LOAD_SETUP);
1930         RT_TIMING_TIME_DIFF(time_setup     , time_fields    , RT_TIMING_LOAD_FIELDS);
1931         RT_TIMING_TIME_DIFF(time_fields    , time_methods   , RT_TIMING_LOAD_METHODS);
1932         RT_TIMING_TIME_DIFF(time_methods   , time_classrefs , RT_TIMING_LOAD_CLASSREFS);
1933         RT_TIMING_TIME_DIFF(time_classrefs , time_descs     , RT_TIMING_LOAD_DESCS);
1934         RT_TIMING_TIME_DIFF(time_descs     , time_setrefs   , RT_TIMING_LOAD_SETREFS);
1935         RT_TIMING_TIME_DIFF(time_setrefs   , time_parsefds  , RT_TIMING_LOAD_PARSEFDS);
1936         RT_TIMING_TIME_DIFF(time_parsefds  , time_parsemds  , RT_TIMING_LOAD_PARSEMDS);
1937         RT_TIMING_TIME_DIFF(time_parsemds  , time_parsecpool, RT_TIMING_LOAD_PARSECP);
1938         RT_TIMING_TIME_DIFF(time_parsecpool, time_verify    , RT_TIMING_LOAD_VERIFY);
1939         RT_TIMING_TIME_DIFF(time_verify    , time_attrs     , RT_TIMING_LOAD_ATTRS);
1940         RT_TIMING_TIME_DIFF(time_start     , time_attrs     , RT_TIMING_LOAD_TOTAL);
1941
1942         return true;
1943 }
1944
1945
1946 /* load_class_from_classbuffer *************************************************
1947
1948    Convenience wrapper for load_class_from_classbuffer.
1949
1950    SYNCHRONIZATION:
1951        This function is NOT synchronized!
1952    
1953 *******************************************************************************/
1954
1955 classinfo *load_class_from_classbuffer(classbuffer *cb)
1956 {
1957         classinfo *c;
1958         bool       result;
1959
1960         /* Get the classbuffer's class. */
1961
1962         c = cb->clazz;
1963
1964         /* Check if the class is already loaded. */
1965
1966         if (c->state & CLASS_LOADED)
1967                 return c;
1968
1969 #if defined(ENABLE_STATISTICS)
1970         if (opt_stat)
1971                 count_class_loads++;
1972 #endif
1973
1974 #if !defined(NDEBUG)
1975         if (loadverbose)
1976                 log_message_class("Loading class: ", c);
1977 #endif
1978
1979         /* Class is currently loading. */
1980
1981         c->state |= CLASS_LOADING;
1982
1983         /* Parse the classbuffer. */
1984
1985         result = load_class_from_classbuffer_intern(cb);
1986
1987         /* An error occurred. */
1988
1989         if (result == false) {
1990                 /* Revert loading state. */
1991
1992                 c->state = (c->state & ~CLASS_LOADING);
1993
1994                 return NULL;
1995         }
1996
1997         /* Revert loading state and set loaded. */
1998
1999         c->state = (c->state & ~CLASS_LOADING) | CLASS_LOADED;
2000
2001 #if defined(ENABLE_JVMTI)
2002         /* fire Class Prepare JVMTI event */
2003
2004         if (jvmti)
2005                 jvmti_ClassLoadPrepare(true, c);
2006 #endif
2007
2008 #if !defined(NDEBUG)
2009         if (loadverbose)
2010                 log_message_class("Loading done class: ", c);
2011 #endif
2012
2013         return c;
2014 }
2015
2016
2017 /* load_newly_created_array ****************************************************
2018
2019    Load a newly created array class.
2020
2021         RETURN VALUE:
2022             c....................the array class C has been loaded
2023                 other classinfo......the array class was found in the class cache, 
2024                                      C has been freed
2025             NULL.................an exception has been thrown
2026
2027         Note:
2028                 This is an internal function. Do not use it unless you know exactly
2029                 what you are doing!
2030
2031                 Use one of the load_class_... functions for general array class loading.
2032
2033 *******************************************************************************/
2034
2035 classinfo *load_newly_created_array(classinfo *c, classloader_t *loader)
2036 {
2037         classinfo         *comp = NULL;
2038         methodinfo        *clone;
2039         methoddesc        *clonedesc;
2040         constant_classref *classrefs;
2041         char              *text;
2042         s4                 namelen;
2043         utf               *u;
2044
2045         text    = c->name->text;
2046         namelen = c->name->blength;
2047
2048         /* Check array class name */
2049
2050         if ((namelen < 2) || (text[0] != '[')) {
2051                 exceptions_throw_classnotfoundexception(c->name);
2052                 return NULL;
2053         }
2054
2055         /* Check the element type */
2056
2057         switch (text[1]) {
2058         case '[':
2059                 /* c is an array of arrays. We have to create the component class. */
2060
2061                 u = utf_new(text + 1, namelen - 1);
2062
2063                 comp = load_class_from_classloader(u, loader);
2064
2065                 if (comp == NULL)
2066                         return NULL;
2067
2068                 assert(comp->state & CLASS_LOADED);
2069
2070                 /* the array's flags are that of the component class */
2071                 c->flags = (comp->flags & ~ACC_INTERFACE) | ACC_FINAL | ACC_ABSTRACT;
2072                 c->classloader = comp->classloader;
2073                 break;
2074
2075         case 'L':
2076                 /* c is an array of objects. */
2077
2078                 /* check for cases like `[L;' or `[L[I;' or `[Ljava.lang.Object' */
2079                 if ((namelen < 4) || (text[2] == '[') || (text[namelen - 1] != ';')) {
2080                         exceptions_throw_classnotfoundexception(c->name);
2081                         return NULL;
2082                 }
2083
2084                 u = utf_new(text + 2, namelen - 3);
2085
2086                 if (!(comp = load_class_from_classloader(u, loader)))
2087                         return NULL;
2088
2089                 assert(comp->state & CLASS_LOADED);
2090
2091                 /* the array's flags are that of the component class */
2092                 c->flags = (comp->flags & ~ACC_INTERFACE) | ACC_FINAL | ACC_ABSTRACT;
2093                 c->classloader = comp->classloader;
2094                 break;
2095
2096         default:
2097                 /* c is an array of a primitive type */
2098
2099                 /* check for cases like `[II' and whether the character is a
2100                    valid primitive type */
2101
2102                 if ((namelen > 2) || (Primitive::get_class_by_char(text[1]) == NULL)) {
2103                         exceptions_throw_classnotfoundexception(c->name);
2104                         return NULL;
2105                 }
2106
2107                 /* the accessibility of the array class is public (VM Spec 5.3.3) */
2108                 c->flags = ACC_PUBLIC | ACC_FINAL | ACC_ABSTRACT;
2109                 c->classloader = NULL;
2110         }
2111
2112         assert(class_java_lang_Object);
2113 #if defined(ENABLE_JAVASE)
2114         assert(class_java_lang_Cloneable);
2115         assert(class_java_io_Serializable);
2116 #endif
2117
2118         /* Setup the array class. */
2119
2120         c->super = class_java_lang_Object;
2121
2122 #if defined(ENABLE_JAVASE)
2123
2124         c->interfacescount = 2;
2125     c->interfaces      = MNEW(classinfo*, 2);
2126         c->interfaces[0]   = class_java_lang_Cloneable;
2127         c->interfaces[1]   = class_java_io_Serializable;
2128
2129 #elif defined(ENABLE_JAVAME_CLDC1_1)
2130
2131         c->interfacescount = 0;
2132         c->interfaces      = NULL;
2133
2134 #else
2135 # error unknow Java configuration
2136 #endif
2137
2138         c->methodscount = 1;
2139         c->methods      = MNEW(methodinfo, c->methodscount);
2140
2141         MZERO(c->methods, methodinfo, c->methodscount);
2142
2143         classrefs = MNEW(constant_classref, 2);
2144
2145         CLASSREF_INIT(classrefs[0], c, c->name);
2146         CLASSREF_INIT(classrefs[1], c, utf_java_lang_Object);
2147
2148         /* create descriptor for clone method */
2149         /* we need one paramslot which is reserved for the 'this' parameter */
2150         clonedesc = NEW(methoddesc);
2151         clonedesc->returntype.type = TYPE_ADR;
2152         clonedesc->returntype.classref = classrefs + 1;
2153         clonedesc->returntype.arraydim = 0;
2154         /* initialize params to "empty", add real params below in
2155            descriptor_params_from_paramtypes */
2156         clonedesc->paramcount = 0;
2157         clonedesc->paramslots = 0;
2158         clonedesc->paramtypes[0].classref = classrefs + 0;
2159         clonedesc->params = NULL;
2160
2161         /* create methodinfo */
2162
2163         clone = c->methods;
2164         MSET(clone, 0, methodinfo, 1);
2165
2166         /* ATTENTION: if you delete the ACC_NATIVE below, set
2167            clone->maxlocals=1 (interpreter related) */
2168
2169         clone->mutex      = new Mutex();
2170         clone->flags      = ACC_PUBLIC | ACC_NATIVE;
2171         clone->name       = utf_clone;
2172         clone->descriptor = utf_void__java_lang_Object;
2173         clone->parseddesc = clonedesc;
2174         clone->clazz      = c;
2175
2176         /* parse the descriptor to get the register allocation */
2177
2178         if (!descriptor_params_from_paramtypes(clonedesc, clone->flags))
2179                 return false;
2180
2181         clone->code = NativeStub::generate(clone, BUILTIN_clone);
2182
2183         /* XXX: field: length? */
2184
2185         /* array classes are not loaded from class files */
2186
2187         c->state          |= CLASS_LOADED;
2188         c->parseddescs    = (u1 *) clonedesc;
2189         c->parseddescsize = sizeof(methodinfo);
2190         c->classrefs      = classrefs;
2191         c->classrefcount  = 1;
2192
2193         /* insert class into the loaded class cache */
2194         /* XXX free classinfo if NULL returned? */
2195
2196         return classcache_store(loader, c, true);
2197 }
2198
2199
2200 /* loader_close ****************************************************************
2201
2202    Frees all resources.
2203         
2204 *******************************************************************************/
2205
2206 void loader_close(void)
2207 {
2208         /* empty */
2209 }
2210
2211
2212 /*
2213  * These are local overrides for various environment variables in Emacs.
2214  * Please do not remove this and leave it at the end of the file, where
2215  * Emacs will automagically detect them.
2216  * ---------------------------------------------------------------------
2217  * Local variables:
2218  * mode: c++
2219  * indent-tabs-mode: t
2220  * c-basic-offset: 4
2221  * tab-width: 4
2222  * End:
2223  * vim:noexpandtab:sw=4:ts=4:
2224  */