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