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