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