* src/vmcore/class.h (classinfo): Changed type of super and interfaces
[cacao.git] / src / vmcore / loader.c
1 /* src/vmcore/loader.c - class loader functions
2
3    Copyright (C) 1996-2005, 2006, 2007 R. Grafl, A. Krall, C. Kruegel,
4    C. Oates, R. Obermaisser, M. Platter, M. Probst, S. Ring,
5    E. Steiner, C. Thalinger, D. Thuernbeck, P. Tomsich, C. Ullrich,
6    J. Wenninger, Institut f. Computersprachen - TU Wien
7
8    This file is part of CACAO.
9
10    This program is free software; you can redistribute it and/or
11    modify it under the terms of the GNU General Public License as
12    published by the Free Software Foundation; either version 2, or (at
13    your option) any later version.
14
15    This program is distributed in the hope that it will be useful, but
16    WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18    General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with this program; if not, write to the Free Software
22    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
23    02110-1301, USA.
24
25 */
26
27
28 #include "config.h"
29
30 #include <stdlib.h>
31 #include <string.h>
32 #include <assert.h>
33
34 #include "vm/types.h"
35
36 #include "mm/memory.h"
37
38 #include "native/llni.h"
39
40 #include "threads/lock-common.h"
41
42 #include "toolbox/hashtable.h"
43 #include "toolbox/logging.h"
44
45 #include "vm/builtin.h"
46 #include "vm/exceptions.h"
47 #include "vm/global.h"
48 #include "vm/primitive.h"
49 #include "vm/resolve.h"
50 #include "vm/stringlocal.h"
51 #include "vm/vm.h"
52
53 #include "vm/jit_interface.h"
54
55 #if defined(ENABLE_JAVASE)
56 # include "vmcore/annotation.h"
57 # include "vmcore/stackmap.h"
58 #endif
59
60 #include "vmcore/classcache.h"
61 #include "vmcore/field.h"
62 #include "vmcore/linker.h"
63 #include "vmcore/loader.h"
64 #include "vmcore/method.h"
65 #include "vmcore/options.h"
66 #include "vmcore/rt-timing.h"
67
68 #if defined(ENABLE_STATISTICS)
69 # include "vmcore/statistics.h"
70 #endif
71
72 #include "vmcore/suck.h"
73
74 #if defined(ENABLE_ZLIB)
75 # include "vmcore/zip.h"
76 #endif
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 *******************************************************************************/
94  
95 void loader_preinit(void)
96 {
97 #if defined(ENABLE_THREADS)
98         list_classpath_entry *lce;
99
100         /* Initialize the monitor pointer for zip/jar file locking. */
101
102         for (lce = list_first(list_classpath_entries); lce != NULL;
103                  lce = list_next(list_classpath_entries, lce)) {
104                 if (lce->type == CLASSPATH_ARCHIVE)
105                         LOCK_INIT_OBJECT_LOCK(lce);
106         }
107 #endif
108
109         /* initialize classloader hashtable, 10 entries should be enough */
110
111         hashtable_classloader = NEW(hashtable);
112         hashtable_create(hashtable_classloader, 10);
113
114         /* Load the most basic class. */
115
116         if (!(class_java_lang_Object = load_class_bootstrap(utf_java_lang_Object)))
117                 vm_abort("loader_preinit: loading java/lang/Object failed");
118
119 #if defined(ENABLE_JAVASE)
120         if (!(class_java_lang_Cloneable =
121                   load_class_bootstrap(utf_java_lang_Cloneable)))
122                 vm_abort("loader_preinit: loading java/lang/Cloneable failed");
123
124         if (!(class_java_io_Serializable =
125                   load_class_bootstrap(utf_java_io_Serializable)))
126                 vm_abort("loader_preinit: loading java/io/Serializable failed");
127 #endif
128 }
129
130
131 /* loader_init *****************************************************************
132
133    Loads all classes required in the VM.
134
135 *******************************************************************************/
136  
137 void loader_init(void)
138 {
139         /* Load primitive-type wrapping classes. */
140
141 #if defined(ENABLE_JAVASE)
142         if (!(class_java_lang_Void = load_class_bootstrap(utf_java_lang_Void)))
143                 vm_abort("loader_init: loading failed");
144 #endif
145
146         if (!(class_java_lang_Boolean =
147                   load_class_bootstrap(utf_java_lang_Boolean)))
148                 vm_abort("loader_init: loading failed");
149
150         if (!(class_java_lang_Byte = load_class_bootstrap(utf_java_lang_Byte)))
151                 vm_abort("loader_init: loading failed");
152
153         if (!(class_java_lang_Character =
154                   load_class_bootstrap(utf_java_lang_Character)))
155                 vm_abort("loader_init: loading failed");
156
157         if (!(class_java_lang_Short = load_class_bootstrap(utf_java_lang_Short)))
158                 vm_abort("loader_init: loading failed");
159
160         if (!(class_java_lang_Integer =
161                   load_class_bootstrap(utf_java_lang_Integer)))
162                 vm_abort("loader_init: loading failed");
163
164         if (!(class_java_lang_Long = load_class_bootstrap(utf_java_lang_Long)))
165                 vm_abort("loader_init: loading failed");
166
167         if (!(class_java_lang_Float = load_class_bootstrap(utf_java_lang_Float)))
168                 vm_abort("loader_init: loading failed");
169
170         if (!(class_java_lang_Double = load_class_bootstrap(utf_java_lang_Double)))
171                 vm_abort("loader_init: loading failed");
172
173         /* Load important system classes. */
174
175         if (!(class_java_lang_Class = load_class_bootstrap(utf_java_lang_Class)))
176                 vm_abort("loader_init: loading failed");
177
178         if (!(class_java_lang_String = load_class_bootstrap(utf_java_lang_String)))
179                 vm_abort("loader_init: loading failed");
180
181 #if defined(ENABLE_JAVASE)
182         if (!(class_java_lang_ClassLoader =
183                   load_class_bootstrap(utf_java_lang_ClassLoader)))
184                 vm_abort("loader_init: loading failed");
185
186         if (!(class_java_lang_SecurityManager =
187                   load_class_bootstrap(utf_java_lang_SecurityManager)))
188                 vm_abort("loader_init: loading failed");
189 #endif
190
191         if (!(class_java_lang_System = load_class_bootstrap(utf_java_lang_System)))
192                 vm_abort("loader_init: loading failed");
193
194         if (!(class_java_lang_Thread =
195                   load_class_bootstrap(utf_new_char("java/lang/Thread"))))
196                 vm_abort("loader_init: loading failed");
197
198 #if defined(ENABLE_JAVASE)
199         if (!(class_java_lang_ThreadGroup =
200                   load_class_bootstrap(utf_java_lang_ThreadGroup)))
201                 vm_abort("loader_init: loading failed");
202 #endif
203
204 #if defined(WITH_CLASSPATH_GNU)
205         if (!(class_java_lang_VMSystem =
206                   load_class_bootstrap(utf_new_char("java/lang/VMSystem"))))
207                 vm_abort("loader_init: loading failed");
208
209         if (!(class_java_lang_VMThread =
210                   load_class_bootstrap(utf_new_char("java/lang/VMThread"))))
211                 vm_abort("loader_init: loading failed");
212 #endif
213
214
215         /* some classes which may be used more often */
216
217 #if defined(ENABLE_JAVASE)
218         if (!(class_java_lang_StackTraceElement =
219                   load_class_bootstrap(utf_java_lang_StackTraceElement)))
220                 vm_abort("loader_init: loading failed");
221
222         if (!(class_java_lang_reflect_Constructor =
223                   load_class_bootstrap(utf_java_lang_reflect_Constructor)))
224                 vm_abort("loader_init: loading failed");
225
226         if (!(class_java_lang_reflect_Field =
227                   load_class_bootstrap(utf_java_lang_reflect_Field)))
228                 vm_abort("loader_init: loading failed");
229
230         if (!(class_java_lang_reflect_Method =
231                   load_class_bootstrap(utf_java_lang_reflect_Method)))
232                 vm_abort("loader_init: loading failed");
233
234         if (!(class_java_security_PrivilegedAction =
235                   load_class_bootstrap(utf_new_char("java/security/PrivilegedAction"))))
236                 vm_abort("loader_init: loading failed");
237
238         if (!(class_java_util_Vector = load_class_bootstrap(utf_java_util_Vector)))
239                 vm_abort("loader_init: loading failed");
240
241 # if defined(WITH_CLASSPATH_SUN)
242         if (!(class_sun_reflect_MagicAccessorImpl =
243                   load_class_bootstrap(utf_new_char("sun/reflect/MagicAccessorImpl"))))
244                 vm_abort("loader_init: loading failed");
245 # endif
246
247         if (!(arrayclass_java_lang_Object =
248                   load_class_bootstrap(utf_new_char("[Ljava/lang/Object;"))))
249                 vm_abort("loader_init: loading failed");
250
251 # if defined(ENABLE_ANNOTATIONS)
252         /* needed by annotation support */
253         if (!(class_sun_reflect_ConstantPool = 
254                   load_class_bootstrap(utf_new_char("sun/reflect/ConstantPool"))))
255                 vm_abort("loader_init: loading failed");
256
257 #  if defined(WITH_CLASSPATH_GNU)
258         /* needed by GNU Classpaths annotation support */
259         if (!(class_sun_reflect_annotation_AnnotationParser = 
260                   load_class_bootstrap(utf_new_char("sun/reflect/annotation/AnnotationParser"))))
261                 vm_abort("loader_init: loading failed");
262 #  endif
263 # endif
264 #endif
265 }
266
267
268 /* loader_hashtable_classloader_add ********************************************
269
270    Adds an entry to the classloader hashtable.
271
272    REMEMBER: Also use this to register native loaders!
273
274 *******************************************************************************/
275
276 classloader *loader_hashtable_classloader_add(java_handle_t *cl)
277 {
278         hashtable_classloader_entry *cle;
279         u4   key;
280         u4   slot;
281
282         if (cl == NULL)
283                 return NULL;
284
285         LOCK_MONITOR_ENTER(hashtable_classloader->header);
286
287         LLNI_CRITICAL_START;
288
289         /* key for entry is the hashcode of the classloader;
290            aligned to 16-byte boundaries */
291
292 #if defined(ENABLE_GC_CACAO)
293         key  = heap_get_hashcode(LLNI_DIRECT(cl)) >> 4;
294 #else
295         key  = ((u4) (ptrint) cl) >> 4;
296 #endif
297
298         slot = key & (hashtable_classloader->size - 1);
299         cle  = hashtable_classloader->ptr[slot];
300
301         /* search hashchain for existing entry */
302
303         while (cle) {
304                 if (cle->object == LLNI_DIRECT(cl))
305                         break;
306
307                 cle = cle->hashlink;
308         }
309
310         LLNI_CRITICAL_END;
311
312         /* if no classloader was found, we create a new entry here */
313
314         if (cle == NULL) {
315                 cle = NEW(hashtable_classloader_entry);
316
317 #if defined(ENABLE_GC_CACAO)
318                 /* register the classloader object with the GC */
319
320                 gc_reference_register(&(cle->object), GC_REFTYPE_CLASSLOADER);
321 #endif
322
323                 LLNI_CRITICAL_START;
324
325                 cle->object = LLNI_DIRECT(cl);
326
327                 LLNI_CRITICAL_END;
328
329                 /* insert entry into hashtable */
330
331                 cle->hashlink = hashtable_classloader->ptr[slot];
332                 hashtable_classloader->ptr[slot] = cle;
333
334                 /* update number of entries */
335
336                 hashtable_classloader->entries++;
337         }
338
339
340         LOCK_MONITOR_EXIT(hashtable_classloader->header);
341
342         return cle;
343 }
344
345
346 /* loader_hashtable_classloader_find *******************************************
347
348    Find an entry in the classloader hashtable.
349
350 *******************************************************************************/
351
352 classloader *loader_hashtable_classloader_find(java_handle_t *cl)
353 {
354         hashtable_classloader_entry *cle;
355         u4   key;
356         u4   slot;
357
358         if (cl == NULL)
359                 return NULL;
360
361         LLNI_CRITICAL_START;
362
363         /* key for entry is the hashcode of the classloader;
364            aligned to 16-byte boundaries */
365
366 #if defined(ENABLE_GC_CACAO)
367         key  = heap_get_hashcode(LLNI_DIRECT(cl)) >> 4;
368 #else
369         key  = ((u4) (ptrint) cl) >> 4;
370 #endif
371
372         slot = key & (hashtable_classloader->size - 1);
373         cle  = hashtable_classloader->ptr[slot];
374
375         /* search hashchain for existing entry */
376
377         while (cle) {
378                 if (cle->object == LLNI_DIRECT(cl))
379                         break;
380
381                 cle = cle->hashlink;
382         }
383
384         LLNI_CRITICAL_END;
385
386         return cle;
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         s4                       slot;
402         hashtable_zipfile_entry *htzfe;
403         utf                     *u;
404 #endif
405
406         for (lce = list_first(list_classpath_entries); lce != NULL;
407                  lce = list_next(list_classpath_entries, lce)) {
408 #if defined(ENABLE_ZLIB)
409                 if (lce->type == CLASSPATH_ARCHIVE) {
410                         /* get the classes hashtable */
411
412                         ht = lce->htclasses;
413
414                         for (slot = 0; slot < ht->size; slot++) {
415                                 htzfe = (hashtable_zipfile_entry *) ht->ptr[slot];
416
417                                 for (; htzfe; htzfe = htzfe->hashlink) {
418                                         u = htzfe->filename;
419
420                                         /* skip all entries in META-INF and .properties,
421                        .png files */
422
423                                         if (!strncmp(u->text, "META-INF", strlen("META-INF")) ||
424                                                 strstr(u->text, ".properties") ||
425                                                 strstr(u->text, ".png"))
426                                                 continue;
427
428                                         /* load class from bootstrap classloader */
429
430                                         if (!load_class_bootstrap(u)) {
431                                                 fprintf(stderr, "Error loading: ");
432                                                 utf_fprint_printable_ascii_classname(stderr, u);
433                                                 fprintf(stderr, "\n");
434
435 #if !defined(NDEBUG)
436                                                 /* print out exception and cause */
437
438                                                 exceptions_print_current_exception();
439 #endif
440                                         }
441                                 }
442                         }
443
444                 } else {
445 #endif
446 #if defined(ENABLE_ZLIB)
447                 }
448 #endif
449         }
450 }
451
452
453 /* loader_skip_attribute_body **************************************************
454
455    Skips an attribute the attribute_name_index has already been read.
456         
457    attribute_info {
458        u2 attribute_name_index;
459        u4 attribute_length;
460        u1 info[attribute_length];
461    }
462
463 *******************************************************************************/
464
465 bool loader_skip_attribute_body(classbuffer *cb)
466 {
467         u4 attribute_length;
468
469         if (!suck_check_classbuffer_size(cb, 4))
470                 return false;
471
472         attribute_length = suck_u4(cb);
473
474         if (!suck_check_classbuffer_size(cb, attribute_length))
475                 return false;
476
477         suck_skip_nbytes(cb, attribute_length);
478
479         return true;
480 }
481
482
483 /* load_constantpool ***********************************************************
484
485    Loads the constantpool of a class, the entries are transformed into
486    a simpler format by resolving references (a detailed overview of
487    the compact structures can be found in global.h).
488
489 *******************************************************************************/
490
491 static bool load_constantpool(classbuffer *cb, descriptor_pool *descpool)
492 {
493
494         /* The following structures are used to save information which cannot be 
495            processed during the first pass. After the complete constantpool has 
496            been traversed the references can be resolved. 
497            (only in specific order)                                                */
498         
499         /* CONSTANT_Class entries */
500         typedef struct forward_class {
501                 struct forward_class *next;
502                 u2 thisindex;
503                 u2 name_index;
504         } forward_class;
505
506         /* CONSTANT_String */
507         typedef struct forward_string {
508                 struct forward_string *next;
509                 u2 thisindex;
510                 u2 string_index;
511         } forward_string;
512
513         /* CONSTANT_NameAndType */
514         typedef struct forward_nameandtype {
515                 struct forward_nameandtype *next;
516                 u2 thisindex;
517                 u2 name_index;
518                 u2 sig_index;
519         } forward_nameandtype;
520
521         /* CONSTANT_Fieldref, CONSTANT_Methodref or CONSTANT_InterfaceMethodref */
522         typedef struct forward_fieldmethint {
523                 struct forward_fieldmethint *next;
524                 u2 thisindex;
525                 u1 tag;
526                 u2 class_index;
527                 u2 nameandtype_index;
528         } forward_fieldmethint;
529
530
531         classinfo *c;
532         u4 idx;
533
534         forward_class *forward_classes = NULL;
535         forward_string *forward_strings = NULL;
536         forward_nameandtype *forward_nameandtypes = NULL;
537         forward_fieldmethint *forward_fieldmethints = NULL;
538
539         forward_class *nfc;
540         forward_string *nfs;
541         forward_nameandtype *nfn;
542         forward_fieldmethint *nff;
543
544         u4 cpcount;
545         u1 *cptags;
546         voidptr *cpinfos;
547
548         c = cb->class;
549
550         /* number of entries in the constant_pool table plus one */
551         if (!suck_check_classbuffer_size(cb, 2))
552                 return false;
553
554         cpcount = c->cpcount = suck_u2(cb);
555
556         /* allocate memory */
557         cptags  = c->cptags  = MNEW(u1, cpcount);
558         cpinfos = c->cpinfos = MNEW(voidptr, cpcount);
559
560         if (cpcount < 1) {
561                 exceptions_throw_classformaterror(c, "Illegal constant pool size");
562                 return false;
563         }
564         
565 #if defined(ENABLE_STATISTICS)
566         if (opt_stat)
567                 count_const_pool_len += (sizeof(u1) + sizeof(voidptr)) * cpcount;
568 #endif
569         
570         /* initialize constantpool */
571         for (idx = 0; idx < cpcount; idx++) {
572                 cptags[idx] = CONSTANT_UNUSED;
573                 cpinfos[idx] = NULL;
574         }
575
576                         
577         /******* first pass *******/
578         /* entries which cannot be resolved now are written into 
579            temporary structures and traversed again later        */
580                    
581         idx = 1;
582         while (idx < cpcount) {
583                 u4 t;
584
585                 /* get constant type */
586                 if (!suck_check_classbuffer_size(cb, 1))
587                         return false;
588
589                 t = suck_u1(cb);
590
591                 switch (t) {
592                 case CONSTANT_Class:
593                         nfc = DNEW(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                         nfs = DNEW(forward_string);
610                                 
611                         nfs->next = forward_strings;
612                         forward_strings = nfs;
613                                 
614                         nfs->thisindex = idx;
615
616                         /* reference to CONSTANT_Utf8_info with string characters */
617                         if (!suck_check_classbuffer_size(cb, 2))
618                                 return false;
619
620                         nfs->string_index = suck_u2(cb);
621                                 
622                         idx++;
623                         break;
624
625                 case CONSTANT_NameAndType:
626                         nfn = DNEW(forward_nameandtype);
627                                 
628                         nfn->next = forward_nameandtypes;
629                         forward_nameandtypes = nfn;
630                                 
631                         nfn->thisindex = idx;
632
633                         if (!suck_check_classbuffer_size(cb, 2 + 2))
634                                 return false;
635
636                         /* reference to CONSTANT_Utf8_info containing simple name */
637                         nfn->name_index = suck_u2(cb);
638
639                         /* reference to CONSTANT_Utf8_info containing field or method
640                            descriptor */
641                         nfn->sig_index = suck_u2(cb);
642                                 
643                         idx++;
644                         break;
645
646                 case CONSTANT_Fieldref:
647                 case CONSTANT_Methodref:
648                 case CONSTANT_InterfaceMethodref:
649                         nff = DNEW(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 =
795                         class_getconstant(c, forward_classes->name_index, CONSTANT_Utf8);
796                 if (!name)
797                         return false;
798
799 #ifdef ENABLE_VERIFIER
800                 if (opt_verify && !is_valid_name_utf(name)) {
801                         exceptions_throw_classformaterror(c, "Class reference with invalid name");
802                         return false;
803                 }
804 #endif /* ENABLE_VERIFIER */
805
806                 /* add all class references to the descriptor_pool */
807
808                 if (!descriptor_pool_add_class(descpool, name))
809                         return false;
810
811                 cptags[forward_classes->thisindex] = CONSTANT_Class;
812
813                 /* the classref is created later */
814                 cpinfos[forward_classes->thisindex] = name;
815
816                 nfc = forward_classes;
817                 forward_classes = forward_classes->next;
818         }
819
820         while (forward_strings) {
821                 utf *text =
822                         class_getconstant(c, forward_strings->string_index, CONSTANT_Utf8);
823                 if (!text)
824                         return false;
825
826                 /* resolve utf-string */
827                 cptags[forward_strings->thisindex] = CONSTANT_String;
828                 cpinfos[forward_strings->thisindex] = text;
829                 
830                 nfs = forward_strings;
831                 forward_strings = forward_strings->next;
832         }
833
834         while (forward_nameandtypes) {
835                 constant_nameandtype *cn = NEW(constant_nameandtype);   
836
837 #if defined(ENABLE_STATISTICS)
838                 if (opt_stat)
839                         count_const_pool_len += sizeof(constant_nameandtype);
840 #endif
841
842                 /* resolve simple name and descriptor */
843                 cn->name = class_getconstant(c,
844                                                                          forward_nameandtypes->name_index,
845                                                                          CONSTANT_Utf8);
846                 if (!cn->name)
847                         return false;
848
849                 cn->descriptor = class_getconstant(c,
850                                                                                    forward_nameandtypes->sig_index,
851                                                                                    CONSTANT_Utf8);
852                 if (!cn->descriptor)
853                         return false;
854
855 #ifdef ENABLE_VERIFIER
856                 if (opt_verify) {
857                         /* check name */
858                         if (!is_valid_name_utf(cn->name)) {
859                                 exceptions_throw_classformaterror(c,
860                                                                                                   "Illegal Field name \"%s\"",
861                                                                                                   cn->name->text);
862
863                                 return false;
864                         }
865
866                         /* disallow referencing <clinit> among others */
867                         if (cn->name->text[0] == '<' && cn->name != utf_init) {
868                                 exceptions_throw_classformaterror(c, "Illegal reference to special method");
869                                 return false;
870                         }
871                 }
872 #endif /* ENABLE_VERIFIER */
873
874                 cptags[forward_nameandtypes->thisindex] = CONSTANT_NameAndType;
875                 cpinfos[forward_nameandtypes->thisindex] = cn;
876
877                 nfn = forward_nameandtypes;
878                 forward_nameandtypes = forward_nameandtypes->next;
879         }
880
881         while (forward_fieldmethints) {
882                 constant_nameandtype *nat;
883                 constant_FMIref *fmi = NEW(constant_FMIref);
884
885 #if defined(ENABLE_STATISTICS)
886                 if (opt_stat)
887                         count_const_pool_len += sizeof(constant_FMIref);
888 #endif
889                 /* resolve simple name and descriptor */
890
891                 nat = class_getconstant(c,
892                                                                 forward_fieldmethints->nameandtype_index,
893                                                                 CONSTANT_NameAndType);
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->class;
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         if (!(*signature = class_getconstant(c, signature_index, CONSTANT_Utf8)))
966                 return false;
967
968         return true;
969 }
970 #endif /* defined(ENABLE_JAVASE) */
971
972
973 /* load_class_from_sysloader ***************************************************
974
975    Load the class with the given name using the system class loader
976
977    IN:
978        name.............the classname
979
980    RETURN VALUE:
981        the loaded class, or
982            NULL if an exception has been thrown
983
984 *******************************************************************************/
985
986 classinfo *load_class_from_sysloader(utf *name)
987 {
988         methodinfo    *m;
989         java_handle_t *clo;
990         classloader   *cl;
991         classinfo     *c;
992
993         assert(class_java_lang_Object);
994         assert(class_java_lang_ClassLoader);
995         assert(class_java_lang_ClassLoader->state & CLASS_LINKED);
996         
997         m = class_resolveclassmethod(class_java_lang_ClassLoader,
998                                                                  utf_getSystemClassLoader,
999                                                                  utf_void__java_lang_ClassLoader,
1000                                                                  class_java_lang_Object,
1001                                                                  false);
1002
1003         if (!m)
1004                 return false;
1005
1006         clo = vm_call_method(m, NULL);
1007
1008         if (!clo)
1009                 return false;
1010
1011         cl = loader_hashtable_classloader_add(clo);
1012
1013         c = load_class_from_classloader(name, cl);
1014
1015         return c;
1016 }
1017
1018
1019 /* load_class_from_classloader *************************************************
1020
1021    Load the class with the given name using the given user-defined class loader.
1022
1023    IN:
1024        name.............the classname
1025            cl...............user-defined class loader
1026            
1027    RETURN VALUE:
1028        the loaded class, or
1029            NULL if an exception has been thrown
1030
1031 *******************************************************************************/
1032
1033 classinfo *load_class_from_classloader(utf *name, classloader *cl)
1034 {
1035         java_handle_t *o;
1036         classinfo     *c;
1037         classinfo     *tmpc;
1038         java_handle_t *string;
1039 #if defined(ENABLE_RT_TIMING)
1040         struct timespec time_start, time_lookup, time_prepare, time_java, 
1041                                         time_cache;
1042 #endif
1043
1044         RT_TIMING_GET_TIME(time_start);
1045
1046         assert(name);
1047
1048         /* lookup if this class has already been loaded */
1049
1050         c = classcache_lookup(cl, name);
1051
1052         RT_TIMING_GET_TIME(time_lookup);
1053         RT_TIMING_TIME_DIFF(time_start,time_lookup,RT_TIMING_LOAD_CL_LOOKUP);
1054
1055         if (c != NULL)
1056                 return c;
1057
1058         /* if other class loader than bootstrap, call it */
1059
1060         if (cl != NULL) {
1061                 methodinfo *lc;
1062                 char       *text;
1063                 s4          namelen;
1064
1065                 text = name->text;
1066                 namelen = name->blength;
1067
1068                 /* handle array classes */
1069                 if (text[0] == '[') {
1070                         classinfo *comp;
1071                         utf       *u;
1072
1073                         switch (text[1]) {
1074                         case 'L':
1075                                 /* check for cases like `[L;' or `[L[I;' or `[Ljava.lang.Object' */
1076                                 if (namelen < 4 || text[2] == '[' || text[namelen - 1] != ';') {
1077                                         exceptions_throw_classnotfoundexception(name);
1078                                         return false;
1079                                 }
1080
1081                                 u = utf_new(text + 2, namelen - 3);
1082
1083                                 if (!(comp = load_class_from_classloader(u, cl)))
1084                                         return false;
1085
1086                                 /* create the array class */
1087
1088                                 c = class_array_of(comp, false);
1089
1090                                 tmpc = classcache_store(cl, c, true);
1091
1092                                 if (tmpc == NULL) {
1093                                         /* exception, free the loaded class */
1094                                         c->state &= ~CLASS_LOADING;
1095                                         class_free(c);
1096                                 }
1097
1098                                 return tmpc;
1099
1100                         case '[':
1101                                 /* load the component class */
1102
1103                                 u = utf_new(text + 1, namelen - 1);
1104
1105                                 if (!(comp = load_class_from_classloader(u, cl)))
1106                                         return false;
1107
1108                                 /* create the array class */
1109
1110                                 c = class_array_of(comp, false);
1111
1112                                 tmpc = classcache_store(cl, c, true);
1113
1114                                 if (tmpc == NULL) {
1115                                         /* exception, free the loaded class */
1116                                         c->state &= ~CLASS_LOADING;
1117                                         class_free(c);
1118                                 }
1119
1120                                 return tmpc;
1121
1122                         default:
1123                                 /* primitive array classes are loaded by the bootstrap loader */
1124
1125                                 c = load_class_bootstrap(name);
1126
1127                                 return c;
1128                         }
1129                 }
1130                 
1131 #if defined(WITH_CLASSPATH_SUN)
1132                 /* OpenJDK uses this internal function because it's
1133                    synchronized. */
1134
1135                 lc = class_resolveclassmethod(cl->object->vftbl->class,
1136                                                                           utf_loadClassInternal,
1137                                                                           utf_java_lang_String__java_lang_Class,
1138                                                                           NULL,
1139                                                                           true);
1140 #else
1141                 lc = class_resolveclassmethod(cl->object->vftbl->class,
1142                                                                           utf_loadClass,
1143                                                                           utf_java_lang_String__java_lang_Class,
1144                                                                           NULL,
1145                                                                           true);
1146 #endif
1147
1148                 if (lc == NULL)
1149                         return false; /* exception */
1150
1151                 /* move return value into `o' and cast it afterwards to a classinfo* */
1152
1153                 string = javastring_new_slash_to_dot(name);
1154
1155                 RT_TIMING_GET_TIME(time_prepare);
1156
1157 #if defined(ENABLE_HANDLES)
1158                 o = vm_call_method(lc, (java_handle_t *) cl, string);
1159 #else
1160                 o = vm_call_method(lc, cl->object, string);
1161 #endif
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                 /* this normally means, the classpath was not set properly */
1298
1299                 if (name == utf_java_lang_Object)
1300                         vm_abort("java/lang/NoClassDefFoundError: java/lang/Object");
1301
1302                 exceptions_throw_classnotfoundexception(name);
1303
1304                 return NULL;
1305         }
1306
1307         RT_TIMING_GET_TIME(time_suck);
1308         
1309         /* load the class from the buffer */
1310
1311         r = load_class_from_classbuffer(cb);
1312
1313         RT_TIMING_GET_TIME(time_load);
1314         
1315         if (!r) {
1316                 /* the class could not be loaded, free the classinfo struct */
1317
1318                 class_free(c);
1319
1320         } else {
1321                 /* Store this class in the loaded class cache this step also
1322                 checks the loading constraints. If the class has been loaded
1323                 before, the earlier loaded class is returned. */
1324
1325                 classinfo *res = classcache_store(NULL, c, true);
1326
1327                 if (!res) {
1328                         /* exception */
1329                         class_free(c);
1330                 }
1331
1332                 r = res;
1333         }
1334
1335         RT_TIMING_GET_TIME(time_cache);
1336         
1337         /* SUN compatible -verbose:class output */
1338
1339         if (opt_verboseclass && r) {
1340                 printf("[Loaded ");
1341                 utf_display_printable_ascii_classname(name);
1342                 printf(" from %s]\n", cb->path);
1343         }
1344
1345         /* free memory */
1346
1347         suck_stop(cb);
1348
1349 #if defined(ENABLE_STATISTICS)
1350         /* measure time */
1351
1352         if (opt_getloadingtime)
1353                 loadingtime_stop();
1354
1355         if (opt_getcompilingtime)
1356                 compilingtime_start();
1357 #endif
1358
1359         RT_TIMING_TIME_DIFF(time_lookup, time_suck , RT_TIMING_LOAD_BOOT_SUCK);
1360         RT_TIMING_TIME_DIFF(time_suck  , time_load , RT_TIMING_LOAD_BOOT_LOAD);
1361         RT_TIMING_TIME_DIFF(time_load  , time_cache, RT_TIMING_LOAD_BOOT_CACHE);
1362         RT_TIMING_TIME_DIFF(time_lookup, time_cache, RT_TIMING_LOAD_BOOT_TOTAL);
1363
1364         return r;
1365 }
1366
1367
1368 /* load_class_from_classbuffer_intern ******************************************
1369         
1370    Loads a class from a classbuffer into a given classinfo structure.
1371    Super-classes are also loaded at this point and some verfication
1372    checks are done.
1373
1374    SYNCHRONIZATION:
1375        This function is NOT synchronized!
1376    
1377 *******************************************************************************/
1378
1379 static bool load_class_from_classbuffer_intern(classbuffer *cb)
1380 {
1381         classinfo          *c;
1382         classinfo          *tc;
1383         utf                *name;
1384         utf                *supername;
1385         utf               **interfacesnames;
1386         utf                *u;
1387         constant_classref  *cr;
1388         int16_t             index;
1389
1390         u4 i,j;
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         RT_TIMING_GET_TIME(time_start);
1405
1406         /* Get the classbuffer's class. */
1407
1408         c = cb->class;
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 = DMNEW(utf*, c->interfacescount);
1565
1566         for (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 (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 (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 =
1624                 descriptor_pool_get_parsed_descriptors(descpool, &(c->parseddescsize));
1625
1626 #if defined(ENABLE_STATISTICS)
1627         if (opt_stat) {
1628                 descriptor_pool_get_sizes(descpool, &classrefsize, &descsize);
1629                 count_classref_len += classrefsize;
1630                 count_parsed_desc_len += descsize;
1631         }
1632 #endif
1633
1634         RT_TIMING_GET_TIME(time_descs);
1635
1636         /* put the classrefs in the constant pool */
1637
1638         for (i = 0; i < c->cpcount; i++) {
1639                 if (c->cptags[i] == CONSTANT_Class) {
1640                         utf *name = (utf *) c->cpinfos[i];
1641                         c->cpinfos[i] = descriptor_pool_lookup_classref(descpool, name);
1642                 }
1643         }
1644
1645         /* Resolve the super class. */
1646
1647         if (supername != NULL) {
1648                 cr = descriptor_pool_lookup_classref(descpool, supername);
1649
1650                 if (cr == NULL)
1651                         return false;
1652
1653                 /* XXX This should be done better. */
1654                 tc = resolve_classref_or_classinfo_eager(CLASSREF_OR_CLASSINFO(cr), false);
1655
1656                 if (tc == NULL)
1657                         return false;
1658
1659                 /* Interfaces are not allowed as super classes. */
1660
1661                 if (tc->flags & ACC_INTERFACE) {
1662                         exceptions_throw_incompatibleclasschangeerror(c, "class %s has interface %s as super class");
1663                         return false;
1664                 }
1665
1666                 /* Don't allow extending final classes */
1667
1668                 if (tc->flags & ACC_FINAL) {
1669                         exceptions_throw_verifyerror(NULL,
1670                                                                                  "Cannot inherit from final class");
1671                         return false;
1672                 }
1673
1674                 /* Store the super class. */
1675
1676                 c->super = tc;
1677         }
1678
1679         /* Resolve the super interfaces. */
1680
1681         for (i = 0; i < c->interfacescount; i++) {
1682                 u  = interfacesnames[i];
1683                 cr = descriptor_pool_lookup_classref(descpool, u);
1684
1685                 if (cr == NULL)
1686                         return false;
1687
1688                 /* XXX This should be done better. */
1689                 tc = resolve_classref_or_classinfo_eager(CLASSREF_OR_CLASSINFO(cr), false);
1690
1691                 if (tc == NULL)
1692                         return false;
1693
1694                 /* Detect circularity. */
1695
1696                 if (tc == c) {
1697                         exceptions_throw_classcircularityerror(c);
1698                         return false;
1699                 }
1700
1701                 if (!(tc->flags & ACC_INTERFACE)) {
1702                         exceptions_throw_incompatibleclasschangeerror(tc,
1703                                                                                                                   "Implementing class");
1704                         return false;
1705                 }
1706
1707                 /* Store the super interface. */
1708
1709                 c->interfaces[i] = tc;
1710         }
1711
1712         RT_TIMING_GET_TIME(time_setrefs);
1713
1714         /* Parse the field descriptors. */
1715
1716         for (i = 0; i < c->fieldscount; i++) {
1717                 c->fields[i].parseddesc =
1718                         descriptor_pool_parse_field_descriptor(descpool,
1719                                                                                                    c->fields[i].descriptor);
1720                 if (!c->fields[i].parseddesc)
1721                         return false;
1722         }
1723
1724         RT_TIMING_GET_TIME(time_parsefds);
1725
1726         /* parse method descriptors */
1727
1728         for (i = 0; i < c->methodscount; i++) {
1729                 methodinfo *m = &c->methods[i];
1730                 m->parseddesc =
1731                         descriptor_pool_parse_method_descriptor(descpool, m->descriptor,
1732                                                                                                         m->flags, class_get_self_classref(m->class));
1733                 if (!m->parseddesc)
1734                         return false;
1735
1736                 for (j = 0; j < m->rawexceptiontablelength; j++) {
1737                         if (!m->rawexceptiontable[j].catchtype.any)
1738                                 continue;
1739
1740                         if ((m->rawexceptiontable[j].catchtype.ref =
1741                                  descriptor_pool_lookup_classref(descpool,
1742                                                 (utf *) m->rawexceptiontable[j].catchtype.any)) == NULL)
1743                                 return false;
1744                 }
1745
1746                 for (j = 0; j < m->thrownexceptionscount; j++) {
1747                         if (!m->thrownexceptions[j].any)
1748                                 continue;
1749
1750                         if ((m->thrownexceptions[j].ref = descriptor_pool_lookup_classref(descpool,
1751                                                 (utf *) m->thrownexceptions[j].any)) == NULL)
1752                                 return false;
1753                 }
1754         }
1755
1756         RT_TIMING_GET_TIME(time_parsemds);
1757
1758         /* parse the loaded descriptors */
1759
1760         for (i = 0; i < c->cpcount; i++) {
1761                 constant_FMIref *fmi;
1762                 s4               index;
1763
1764                 switch (c->cptags[i]) {
1765                 case CONSTANT_Fieldref:
1766                         fmi = (constant_FMIref *) c->cpinfos[i];
1767                         fmi->parseddesc.fd =
1768                                 descriptor_pool_parse_field_descriptor(descpool,
1769                                                                                                            fmi->descriptor);
1770                         if (!fmi->parseddesc.fd)
1771                                 return false;
1772
1773                         index = fmi->p.index;
1774                         fmi->p.classref =
1775                                 (constant_classref *) class_getconstant(c, index,
1776                                                                                                                 CONSTANT_Class);
1777                         if (!fmi->p.classref)
1778                                 return false;
1779                         break;
1780                 case CONSTANT_Methodref:
1781                 case CONSTANT_InterfaceMethodref:
1782                         fmi = (constant_FMIref *) c->cpinfos[i];
1783                         index = fmi->p.index;
1784                         fmi->p.classref =
1785                                 (constant_classref *) class_getconstant(c, index,
1786                                                                                                                 CONSTANT_Class);
1787                         if (!fmi->p.classref)
1788                                 return false;
1789                         fmi->parseddesc.md =
1790                                 descriptor_pool_parse_method_descriptor(descpool,
1791                                                                                                                 fmi->descriptor,
1792                                                                                                                 ACC_UNDEF,
1793                                                                                                                 fmi->p.classref);
1794                         if (!fmi->parseddesc.md)
1795                                 return false;
1796                         break;
1797                 }
1798         }
1799
1800         RT_TIMING_GET_TIME(time_parsecpool);
1801
1802 #ifdef ENABLE_VERIFIER
1803         /* Check if all fields and methods can be uniquely
1804          * identified by (name,descriptor). */
1805
1806         if (opt_verify) {
1807                 /* We use a hash table here to avoid making the
1808                  * average case quadratic in # of methods, fields.
1809                  */
1810                 static int shift = 0;
1811                 u2 *hashtab;
1812                 u2 *next; /* for chaining colliding hash entries */
1813                 size_t len;
1814                 size_t hashlen;
1815                 u2 index;
1816                 u2 old;
1817
1818                 /* Allocate hashtable */
1819                 len = c->methodscount;
1820                 if (len < c->fieldscount) len = c->fieldscount;
1821                 hashlen = 5 * len;
1822                 hashtab = MNEW(u2,(hashlen + len));
1823                 next = hashtab + hashlen;
1824
1825                 /* Determine bitshift (to get good hash values) */
1826                 if (!shift) {
1827                         len = sizeof(utf);
1828                         while (len) {
1829                                 len >>= 1;
1830                                 shift++;
1831                         }
1832                 }
1833
1834                 /* Check fields */
1835                 memset(hashtab, 0, sizeof(u2) * (hashlen + len));
1836
1837                 for (i = 0; i < c->fieldscount; ++i) {
1838                         fieldinfo *fi = c->fields + i;
1839
1840                         /* It's ok if we lose bits here */
1841                         index = ((((size_t) fi->name) +
1842                                           ((size_t) fi->descriptor)) >> shift) % hashlen;
1843
1844                         if ((old = hashtab[index])) {
1845                                 old--;
1846                                 next[i] = old;
1847                                 do {
1848                                         if (c->fields[old].name == fi->name &&
1849                                                 c->fields[old].descriptor == fi->descriptor) {
1850                                                 exceptions_throw_classformaterror(c, "Repetitive field name/signature");
1851                                                 return false;
1852                                         }
1853                                 } while ((old = next[old]));
1854                         }
1855                         hashtab[index] = i + 1;
1856                 }
1857
1858                 /* Check methods */
1859                 memset(hashtab, 0, sizeof(u2) * (hashlen + hashlen/5));
1860
1861                 for (i = 0; i < c->methodscount; ++i) {
1862                         methodinfo *mi = c->methods + i;
1863
1864                         /* It's ok if we lose bits here */
1865                         index = ((((size_t) mi->name) +
1866                                           ((size_t) mi->descriptor)) >> shift) % hashlen;
1867
1868                         if ((old = hashtab[index])) {
1869                                 old--;
1870                                 next[i] = old;
1871                                 do {
1872                                         if (c->methods[old].name == mi->name &&
1873                                                 c->methods[old].descriptor == mi->descriptor) {
1874                                                 exceptions_throw_classformaterror(c, "Repetitive method name/signature");
1875                                                 return false;
1876                                         }
1877                                 } while ((old = next[old]));
1878                         }
1879                         hashtab[index] = i + 1;
1880                 }
1881
1882                 MFREE(hashtab, u2, (hashlen + len));
1883         }
1884 #endif /* ENABLE_VERIFIER */
1885
1886         RT_TIMING_GET_TIME(time_verify);
1887
1888 #if defined(ENABLE_STATISTICS)
1889         if (opt_stat) {
1890                 size_classinfo  += sizeof(classinfo*) * c->interfacescount;
1891                 size_fieldinfo  += sizeof(fieldinfo)  * c->fieldscount;
1892                 size_methodinfo += sizeof(methodinfo) * c->methodscount;
1893         }
1894 #endif
1895
1896         /* load attribute structures */
1897
1898         if (!class_load_attributes(cb))
1899                 return false;
1900
1901         /* Pre Java 1.5 version don't check this. This implementation is
1902            like Java 1.5 do it: for class file version 45.3 we don't check
1903            it, older versions are checked. */
1904
1905         if (((ma == 45) && (mi > 3)) || (ma > 45)) {
1906                 /* check if all data has been read */
1907                 s4 classdata_left = ((cb->data + cb->size) - cb->pos);
1908
1909                 if (classdata_left > 0) {
1910                         exceptions_throw_classformaterror(c, "Extra bytes at the end of class file");
1911                         return false;
1912                 }
1913         }
1914
1915         RT_TIMING_GET_TIME(time_attrs);
1916
1917         RT_TIMING_TIME_DIFF(time_start     , time_checks    , RT_TIMING_LOAD_CHECKS);
1918         RT_TIMING_TIME_DIFF(time_checks    , time_ndpool    , RT_TIMING_LOAD_NDPOOL);
1919         RT_TIMING_TIME_DIFF(time_ndpool    , time_cpool     , RT_TIMING_LOAD_CPOOL);
1920         RT_TIMING_TIME_DIFF(time_cpool     , time_setup     , RT_TIMING_LOAD_SETUP);
1921         RT_TIMING_TIME_DIFF(time_setup     , time_fields    , RT_TIMING_LOAD_FIELDS);
1922         RT_TIMING_TIME_DIFF(time_fields    , time_methods   , RT_TIMING_LOAD_METHODS);
1923         RT_TIMING_TIME_DIFF(time_methods   , time_classrefs , RT_TIMING_LOAD_CLASSREFS);
1924         RT_TIMING_TIME_DIFF(time_classrefs , time_descs     , RT_TIMING_LOAD_DESCS);
1925         RT_TIMING_TIME_DIFF(time_descs     , time_setrefs   , RT_TIMING_LOAD_SETREFS);
1926         RT_TIMING_TIME_DIFF(time_setrefs   , time_parsefds  , RT_TIMING_LOAD_PARSEFDS);
1927         RT_TIMING_TIME_DIFF(time_parsefds  , time_parsemds  , RT_TIMING_LOAD_PARSEMDS);
1928         RT_TIMING_TIME_DIFF(time_parsemds  , time_parsecpool, RT_TIMING_LOAD_PARSECP);
1929         RT_TIMING_TIME_DIFF(time_parsecpool, time_verify    , RT_TIMING_LOAD_VERIFY);
1930         RT_TIMING_TIME_DIFF(time_verify    , time_attrs     , RT_TIMING_LOAD_ATTRS);
1931         RT_TIMING_TIME_DIFF(time_start     , time_attrs     , RT_TIMING_LOAD_TOTAL);
1932
1933         return true;
1934 }
1935
1936
1937 /* load_class_from_classbuffer *************************************************
1938
1939    Convenience wrapper for load_class_from_classbuffer.
1940
1941    SYNCHRONIZATION:
1942        This function is NOT synchronized!
1943    
1944 *******************************************************************************/
1945
1946 classinfo *load_class_from_classbuffer(classbuffer *cb)
1947 {
1948         classinfo *c;
1949         int32_t    dumpsize;
1950         bool       result;
1951
1952         /* Get the classbuffer's class. */
1953
1954         c = cb->class;
1955
1956         /* Check if the class is already loaded. */
1957
1958         if (c->state & CLASS_LOADED)
1959                 return c;
1960
1961 #if defined(ENABLE_STATISTICS)
1962         if (opt_stat)
1963                 count_class_loads++;
1964 #endif
1965
1966 #if !defined(NDEBUG)
1967         if (loadverbose)
1968                 log_message_class("Loading class: ", c);
1969 #endif
1970
1971         /* Mark start of dump memory area. */
1972
1973         dumpsize = dump_size();
1974
1975         /* Class is currently loading. */
1976
1977         c->state |= CLASS_LOADING;
1978
1979         /* Parse the classbuffer. */
1980
1981         result = load_class_from_classbuffer_intern(cb);
1982
1983         /* Release dump area. */
1984
1985         dump_release(dumpsize);
1986
1987         /* An error occurred. */
1988
1989         if (result == false) {
1990                 /* Revert loading state. */
1991
1992                 c->state = (c->state & ~CLASS_LOADING);
1993
1994                 return NULL;
1995         }
1996
1997         /* Revert loading state and set loaded. */
1998
1999         c->state = (c->state & ~CLASS_LOADING) | CLASS_LOADED;
2000
2001 #if defined(ENABLE_JVMTI)
2002         /* fire Class Prepare JVMTI event */
2003
2004         if (jvmti)
2005                 jvmti_ClassLoadPrepare(true, c);
2006 #endif
2007
2008 #if !defined(NDEBUG)
2009         if (loadverbose)
2010                 log_message_class("Loading done class: ", c);
2011 #endif
2012
2013         return c;
2014 }
2015
2016
2017 /* load_newly_created_array ****************************************************
2018
2019    Load a newly created array class.
2020
2021         RETURN VALUE:
2022             c....................the array class C has been loaded
2023                 other classinfo......the array class was found in the class cache, 
2024                                      C has been freed
2025             NULL.................an exception has been thrown
2026
2027         Note:
2028                 This is an internal function. Do not use it unless you know exactly
2029                 what you are doing!
2030
2031                 Use one of the load_class_... functions for general array class loading.
2032
2033 *******************************************************************************/
2034
2035 classinfo *load_newly_created_array(classinfo *c, classloader *loader)
2036 {
2037         classinfo         *comp = NULL;
2038         methodinfo        *clone;
2039         methoddesc        *clonedesc;
2040         constant_classref *classrefs;
2041         char              *text;
2042         s4                 namelen;
2043         utf               *u;
2044
2045         text    = c->name->text;
2046         namelen = c->name->blength;
2047
2048         /* Check array class name */
2049
2050         if ((namelen < 2) || (text[0] != '[')) {
2051                 exceptions_throw_classnotfoundexception(c->name);
2052                 return NULL;
2053         }
2054
2055         /* Check the element type */
2056
2057         switch (text[1]) {
2058         case '[':
2059                 /* c is an array of arrays. We have to create the component class. */
2060
2061                 u = utf_new(text + 1, namelen - 1);
2062
2063                 comp = load_class_from_classloader(u, loader);
2064
2065                 if (comp == NULL)
2066                         return NULL;
2067
2068                 assert(comp->state & CLASS_LOADED);
2069
2070                 /* the array's flags are that of the component class */
2071                 c->flags = (comp->flags & ~ACC_INTERFACE) | ACC_FINAL | ACC_ABSTRACT;
2072                 c->classloader = comp->classloader;
2073                 break;
2074
2075         case 'L':
2076                 /* c is an array of objects. */
2077
2078                 /* check for cases like `[L;' or `[L[I;' or `[Ljava.lang.Object' */
2079                 if ((namelen < 4) || (text[2] == '[') || (text[namelen - 1] != ';')) {
2080                         exceptions_throw_classnotfoundexception(c->name);
2081                         return NULL;
2082                 }
2083
2084                 u = utf_new(text + 2, namelen - 3);
2085
2086                 if (!(comp = load_class_from_classloader(u, loader)))
2087                         return NULL;
2088
2089                 assert(comp->state & CLASS_LOADED);
2090
2091                 /* the array's flags are that of the component class */
2092                 c->flags = (comp->flags & ~ACC_INTERFACE) | ACC_FINAL | ACC_ABSTRACT;
2093                 c->classloader = comp->classloader;
2094                 break;
2095
2096         default:
2097                 /* c is an array of a primitive type */
2098
2099                 /* check for cases like `[II' and whether the character is a
2100                    valid primitive type */
2101
2102                 if ((namelen > 2) || (primitive_class_get_by_char(text[1]) == NULL)) {
2103                         exceptions_throw_classnotfoundexception(c->name);
2104                         return NULL;
2105                 }
2106
2107                 /* the accessibility of the array class is public (VM Spec 5.3.3) */
2108                 c->flags = ACC_PUBLIC | ACC_FINAL | ACC_ABSTRACT;
2109                 c->classloader = NULL;
2110         }
2111
2112         assert(class_java_lang_Object);
2113 #if defined(ENABLE_JAVASE)
2114         assert(class_java_lang_Cloneable);
2115         assert(class_java_io_Serializable);
2116 #endif
2117
2118         /* Setup the array class. */
2119
2120         c->super = class_java_lang_Object;
2121
2122 #if defined(ENABLE_JAVASE)
2123
2124         c->interfacescount = 2;
2125     c->interfaces      = MNEW(classinfo*, 2);
2126         c->interfaces[0]   = class_java_lang_Cloneable;
2127         c->interfaces[1]   = class_java_io_Serializable;
2128
2129 #elif defined(ENABLE_JAVAME_CLDC1_1)
2130
2131         c->interfacescount = 0;
2132         c->interfaces      = NULL;
2133
2134 #else
2135 # error unknow Java configuration
2136 #endif
2137
2138         c->methodscount = 1;
2139         c->methods      = MNEW(methodinfo, c->methodscount);
2140
2141         MZERO(c->methods, methodinfo, c->methodscount);
2142
2143         classrefs = MNEW(constant_classref, 2);
2144
2145         CLASSREF_INIT(classrefs[0], c, c->name);
2146         CLASSREF_INIT(classrefs[1], c, utf_java_lang_Object);
2147
2148         /* create descriptor for clone method */
2149         /* we need one paramslot which is reserved for the 'this' parameter */
2150         clonedesc = NEW(methoddesc);
2151         clonedesc->returntype.type = TYPE_ADR;
2152         clonedesc->returntype.classref = classrefs + 1;
2153         clonedesc->returntype.arraydim = 0;
2154         /* initialize params to "empty", add real params below in
2155            descriptor_params_from_paramtypes */
2156         clonedesc->paramcount = 0;
2157         clonedesc->paramslots = 0;
2158         clonedesc->paramtypes[0].classref = classrefs + 0;
2159         clonedesc->params = NULL;
2160
2161         /* create methodinfo */
2162
2163         clone = c->methods;
2164         MSET(clone, 0, methodinfo, 1);
2165
2166 #if defined(ENABLE_THREADS)
2167         lock_init_object_lock(&clone->header);
2168 #endif
2169
2170         /* ATTENTION: if you delete the ACC_NATIVE below, set
2171            clone->maxlocals=1 (interpreter related) */
2172
2173         clone->flags      = ACC_PUBLIC | ACC_NATIVE;
2174         clone->name       = utf_clone;
2175         clone->descriptor = utf_void__java_lang_Object;
2176         clone->parseddesc = clonedesc;
2177         clone->class      = c;
2178
2179         /* parse the descriptor to get the register allocation */
2180
2181         if (!descriptor_params_from_paramtypes(clonedesc, clone->flags))
2182                 return false;
2183
2184         clone->code = codegen_generate_stub_native(clone, BUILTIN_clone);
2185
2186         /* XXX: field: length? */
2187
2188         /* array classes are not loaded from class files */
2189
2190         c->state          |= CLASS_LOADED;
2191         c->parseddescs    = (u1 *) clonedesc;
2192         c->parseddescsize = sizeof(methodinfo);
2193         c->classrefs      = classrefs;
2194         c->classrefcount  = 1;
2195
2196         /* insert class into the loaded class cache */
2197         /* XXX free classinfo if NULL returned? */
2198
2199         return classcache_store(loader, c, true);
2200 }
2201
2202
2203 /* loader_close ****************************************************************
2204
2205    Frees all resources.
2206         
2207 *******************************************************************************/
2208
2209 void loader_close(void)
2210 {
2211         /* empty */
2212 }
2213
2214
2215 /*
2216  * These are local overrides for various environment variables in Emacs.
2217  * Please do not remove this and leave it at the end of the file, where
2218  * Emacs will automagically detect them.
2219  * ---------------------------------------------------------------------
2220  * Local variables:
2221  * mode: c
2222  * indent-tabs-mode: t
2223  * c-basic-offset: 4
2224  * tab-width: 4
2225  * End:
2226  * vim:noexpandtab:sw=4:ts=4:
2227  */