a1d730ccc39f29d7978405fd7c3436cfa10cddd2
[cacao.git] / src / vmcore / loader.c
1 /* src/vmcore/loader.c - class loader functions
2
3    Copyright (C) 1996-2005, 2006, 2007, 2008
4    CACAOVM - Verein zur Foerderung der freien virtuellen Maschine CACAO
5
6    This file is part of CACAO.
7
8    This program is free software; you can redistribute it and/or
9    modify it under the terms of the GNU General Public License as
10    published by the Free Software Foundation; either version 2, or (at
11    your option) any later version.
12
13    This program is distributed in the hope that it will be useful, but
14    WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16    General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program; if not, write to the Free Software
20    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
21    02110-1301, USA.
22
23 */
24
25
26 #include "config.h"
27
28 #include <stdlib.h>
29 #include <string.h>
30 #include <assert.h>
31
32 #include "vm/types.h"
33
34 #include "mm/memory.h"
35
36 #include "native/llni.h"
37
38 #include "threads/lock-common.h"
39
40 #include "toolbox/hashtable.h"
41 #include "toolbox/logging.h"
42
43 #include "vm/builtin.h"
44 #include "vm/exceptions.h"
45 #include "vm/global.h"
46 #include "vm/package.h"
47 #include "vm/primitive.h"
48 #include "vm/resolve.h"
49 #include "vm/stringlocal.h"
50 #include "vm/vm.h"
51
52 #include "vm/jit_interface.h"
53
54 #if defined(ENABLE_JAVASE)
55 # include "vmcore/annotation.h"
56 # include "vmcore/stackmap.h"
57 #endif
58
59 #include "vmcore/classcache.h"
60 #include "vmcore/field.h"
61 #include "vmcore/linker.h"
62 #include "vmcore/loader.h"
63 #include "vmcore/method.h"
64 #include "vmcore/options.h"
65 #include "vmcore/rt-timing.h"
66
67 #if defined(ENABLE_STATISTICS)
68 # include "vmcore/statistics.h"
69 #endif
70
71 #include "vmcore/suck.h"
72
73 #if defined(ENABLE_ZLIB)
74 # include "vmcore/zip.h"
75 #endif
76
77 #if defined(ENABLE_JVMTI)
78 # include "native/jvmti/cacaodbg.h"
79 #endif
80
81
82 /* global variables ***********************************************************/
83
84 static hashtable *hashtable_classloader;
85
86
87 /* loader_preinit **************************************************************
88
89    Initializes the classpath list and loads classes required for the
90    primitive table.
91
92    NOTE: Exceptions thrown during VM initialization are caught in the
93          exception functions themselves.
94
95 *******************************************************************************/
96  
97 void loader_preinit(void)
98 {
99 #if defined(ENABLE_THREADS)
100         list_classpath_entry *lce;
101 #endif
102
103         TRACESUBSYSTEMINITIALIZATION("loader_preinit");
104
105 #if defined(ENABLE_THREADS)
106         /* Initialize the monitor pointer for zip/jar file locking. */
107
108         for (lce = list_first(list_classpath_entries); lce != NULL;
109                  lce = list_next(list_classpath_entries, lce)) {
110                 if (lce->type == CLASSPATH_ARCHIVE)
111                         LOCK_INIT_OBJECT_LOCK(lce);
112         }
113 #endif
114
115         /* initialize classloader hashtable, 10 entries should be enough */
116
117         hashtable_classloader = NEW(hashtable);
118         hashtable_create(hashtable_classloader, 10);
119
120         /* Load the most basic classes. */
121
122         assert(vm_initializing == true);
123
124         class_java_lang_Object     = load_class_bootstrap(utf_java_lang_Object);
125
126 #if defined(ENABLE_JAVASE)
127         class_java_lang_Cloneable  = load_class_bootstrap(utf_java_lang_Cloneable);
128         class_java_io_Serializable = load_class_bootstrap(utf_java_io_Serializable);
129 #endif
130 }
131
132
133 /* loader_init *****************************************************************
134
135    Loads all classes required in the VM.
136
137    NOTE: Exceptions thrown during VM initialization are caught in the
138          exception functions themselves.
139
140 *******************************************************************************/
141  
142 void loader_init(void)
143 {
144         TRACESUBSYSTEMINITIALIZATION("loader_init");
145
146         /* Load primitive-type wrapping classes. */
147
148         assert(vm_initializing == true);
149
150 #if defined(ENABLE_JAVASE)
151         class_java_lang_Void       = load_class_bootstrap(utf_java_lang_Void);
152 #endif
153
154         class_java_lang_Boolean    = load_class_bootstrap(utf_java_lang_Boolean);
155         class_java_lang_Byte       = load_class_bootstrap(utf_java_lang_Byte);
156         class_java_lang_Character  = load_class_bootstrap(utf_java_lang_Character);
157         class_java_lang_Short      = load_class_bootstrap(utf_java_lang_Short);
158         class_java_lang_Integer    = load_class_bootstrap(utf_java_lang_Integer);
159         class_java_lang_Long       = load_class_bootstrap(utf_java_lang_Long);
160         class_java_lang_Float      = load_class_bootstrap(utf_java_lang_Float);
161         class_java_lang_Double     = load_class_bootstrap(utf_java_lang_Double);
162
163         /* Load important system classes. */
164
165         class_java_lang_Class      = load_class_bootstrap(utf_java_lang_Class);
166         class_java_lang_String     = load_class_bootstrap(utf_java_lang_String);
167
168 #if defined(ENABLE_JAVASE)
169         class_java_lang_ClassLoader =
170                 load_class_bootstrap(utf_java_lang_ClassLoader);
171
172         class_java_lang_SecurityManager =
173                 load_class_bootstrap(utf_java_lang_SecurityManager);
174 #endif
175
176         class_java_lang_System     =
177                 load_class_bootstrap(utf_new_char("java/lang/System"));
178
179         class_java_lang_Thread     =
180                 load_class_bootstrap(utf_new_char("java/lang/Thread"));
181
182 #if defined(ENABLE_JAVASE)
183         class_java_lang_ThreadGroup =
184                 load_class_bootstrap(utf_java_lang_ThreadGroup);
185 #endif
186
187         class_java_lang_Throwable  = load_class_bootstrap(utf_java_lang_Throwable);
188
189 #if defined(WITH_JAVA_RUNTIME_LIBRARY_GNU_CLASSPATH)
190         class_java_lang_VMSystem   =
191                 load_class_bootstrap(utf_new_char("java/lang/VMSystem"));
192
193         class_java_lang_VMThread   =
194                 load_class_bootstrap(utf_new_char("java/lang/VMThread"));
195
196         class_java_lang_VMThrowable =
197                 load_class_bootstrap(utf_new_char("java/lang/VMThrowable"));
198 #endif
199
200         /* Important system exceptions. */
201
202         class_java_lang_Exception  = load_class_bootstrap(utf_java_lang_Exception);
203
204         class_java_lang_ClassNotFoundException =
205                 load_class_bootstrap(utf_java_lang_ClassNotFoundException);
206
207         class_java_lang_RuntimeException =
208                 load_class_bootstrap(utf_java_lang_RuntimeException);
209
210         /* Some classes which may be used often. */
211
212 #if defined(ENABLE_JAVASE)
213         class_java_lang_StackTraceElement      = load_class_bootstrap(utf_java_lang_StackTraceElement);
214
215         class_java_lang_reflect_Constructor    = load_class_bootstrap(utf_java_lang_reflect_Constructor);
216         class_java_lang_reflect_Field          = load_class_bootstrap(utf_java_lang_reflect_Field);
217         class_java_lang_reflect_Method         = load_class_bootstrap(utf_java_lang_reflect_Method);
218
219 # if defined(WITH_JAVA_RUNTIME_LIBRARY_GNU_CLASSPATH)
220         class_java_lang_reflect_VMConstructor  = load_class_bootstrap(utf_java_lang_reflect_VMConstructor);
221         class_java_lang_reflect_VMField        = load_class_bootstrap(utf_java_lang_reflect_VMField);
222         class_java_lang_reflect_VMMethod       = load_class_bootstrap(utf_java_lang_reflect_VMMethod);
223 # endif
224
225         class_java_security_PrivilegedAction   = load_class_bootstrap(utf_new_char("java/security/PrivilegedAction"));
226
227         class_java_util_HashMap                = load_class_bootstrap(utf_new_char("java/util/HashMap"));
228         class_java_util_Vector                 = load_class_bootstrap(utf_java_util_Vector);
229
230 # if defined(WITH_JAVA_RUNTIME_LIBRARY_OPENJDK)
231         class_sun_reflect_MagicAccessorImpl =
232                 load_class_bootstrap(utf_new_char("sun/reflect/MagicAccessorImpl"));
233 # endif
234
235         arrayclass_java_lang_Object =
236                 load_class_bootstrap(utf_new_char("[Ljava/lang/Object;"));
237
238 # if defined(ENABLE_ANNOTATIONS)
239         /* needed by annotation support */
240         class_sun_reflect_ConstantPool =
241                 load_class_bootstrap(utf_new_char("sun/reflect/ConstantPool"));
242
243 #  if defined(WITH_JAVA_RUNTIME_LIBRARY_GNU_CLASSPATH)
244         /* needed by GNU Classpaths annotation support */
245         class_sun_reflect_annotation_AnnotationParser =
246                 load_class_bootstrap(utf_new_char("sun/reflect/annotation/AnnotationParser"));
247 #  endif
248 # endif
249 #endif
250 }
251
252
253 /* loader_hashtable_classloader_add ********************************************
254
255    Adds an entry to the classloader hashtable.
256
257    REMEMBER: Also use this to register native loaders!
258
259 *******************************************************************************/
260
261 classloader_t *loader_hashtable_classloader_add(java_handle_t *cl)
262 {
263         hashtable_classloader_entry *cle;
264         u4   key;
265         u4   slot;
266
267         if (cl == NULL)
268                 return NULL;
269
270         LOCK_MONITOR_ENTER(hashtable_classloader->header);
271
272         LLNI_CRITICAL_START;
273
274         /* key for entry is the hashcode of the classloader;
275            aligned to 16-byte boundaries */
276
277         key  = heap_hashcode(LLNI_DIRECT(cl)) >> 4;
278         slot = key & (hashtable_classloader->size - 1);
279         cle  = hashtable_classloader->ptr[slot];
280
281         /* search hashchain for existing entry */
282
283         while (cle) {
284                 if (cle->object == LLNI_DIRECT(cl))
285                         break;
286
287                 cle = cle->hashlink;
288         }
289
290         LLNI_CRITICAL_END;
291
292         /* if no classloader was found, we create a new entry here */
293
294         if (cle == NULL) {
295                 cle = NEW(hashtable_classloader_entry);
296
297 #if defined(ENABLE_GC_CACAO)
298                 /* register the classloader object with the GC */
299
300                 gc_reference_register(&(cle->object), GC_REFTYPE_CLASSLOADER);
301 #endif
302
303                 LLNI_CRITICAL_START;
304
305                 cle->object = LLNI_DIRECT(cl);
306
307                 LLNI_CRITICAL_END;
308
309 /*#define LOADER_DEBUG_CLASSLOADER*/
310 #ifdef LOADER_DEBUG_CLASSLOADER
311                 printf("CLASSLOADER: adding new classloader entry %p for %p: ", cle, cl);
312                 class_print(LLNI_vftbl_direct(cl)->class);
313                 printf("\n");
314                 fflush(stdout);
315 #endif
316
317                 /* insert entry into hashtable */
318
319                 cle->hashlink = hashtable_classloader->ptr[slot];
320                 hashtable_classloader->ptr[slot] = cle;
321
322                 /* update number of entries */
323
324                 hashtable_classloader->entries++;
325         }
326
327
328         LOCK_MONITOR_EXIT(hashtable_classloader->header);
329
330 #if defined(ENABLE_HANDLES)
331         return cle;
332 #else
333         return cl;
334 #endif
335 }
336
337
338 /* loader_hashtable_classloader_find *******************************************
339
340    Find an entry in the classloader hashtable.
341
342 *******************************************************************************/
343
344 classloader_t *loader_hashtable_classloader_find(java_handle_t *cl)
345 {
346         hashtable_classloader_entry *cle;
347         u4   key;
348         u4   slot;
349
350         if (cl == NULL)
351                 return NULL;
352
353         LLNI_CRITICAL_START;
354
355         /* key for entry is the hashcode of the classloader;
356            aligned to 16-byte boundaries */
357
358         key  = heap_hashcode(LLNI_DIRECT(cl)) >> 4;
359         slot = key & (hashtable_classloader->size - 1);
360         cle  = hashtable_classloader->ptr[slot];
361
362         /* search hashchain for existing entry */
363
364         while (cle) {
365                 if (cle->object == LLNI_DIRECT(cl))
366                         break;
367
368                 cle = cle->hashlink;
369         }
370
371 #ifdef LOADER_DEBUG_CLASSLOADER
372         if (cle == NULL) {
373                 printf("CLASSLOADER: unable to find classloader entry for %p: ", cl);
374                 class_print(LLNI_vftbl_direct(cl)->class);
375                 printf("\n");
376                 fflush(stdout);
377         }
378 #endif
379
380         LLNI_CRITICAL_END;
381
382 #if defined(ENABLE_HANDLES)
383         return cle;
384 #else
385         return cl;
386 #endif
387 }
388
389
390 /* loader_load_all_classes *****************************************************
391
392    Loads all classes specified in the BOOTCLASSPATH.
393
394 *******************************************************************************/
395
396 void loader_load_all_classes(void)
397 {
398         list_classpath_entry    *lce;
399 #if defined(ENABLE_ZLIB)
400         hashtable               *ht;
401         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->clazz;
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->clazz;
941
942         /* check remaining bytecode */
943
944         if (!suck_check_classbuffer_size(cb, 4 + 2))
945                 return false;
946
947         /* check attribute length */
948
949         attribute_length = suck_u4(cb);
950
951         if (attribute_length != 2) {
952                 exceptions_throw_classformaterror(c, "Wrong size for VALUE attribute");
953                 return false;
954         }
955
956         if (*signature != NULL) {
957                 exceptions_throw_classformaterror(c, "Multiple Signature attributes");
958                 return false;
959         }
960
961         /* get signature */
962
963         signature_index = suck_u2(cb);
964
965         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_t *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_t *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                 LLNI_class_get(cl, c);
1132
1133 #if defined(WITH_JAVA_RUNTIME_LIBRARY_OPENJDK)
1134                 /* OpenJDK uses this internal function because it's
1135                    synchronized. */
1136
1137                 lc = class_resolveclassmethod(c,
1138                                                                           utf_loadClassInternal,
1139                                                                           utf_java_lang_String__java_lang_Class,
1140                                                                           NULL,
1141                                                                           true);
1142 #else
1143                 lc = class_resolveclassmethod(c,
1144                                                                           utf_loadClass,
1145                                                                           utf_java_lang_String__java_lang_Class,
1146                                                                           NULL,
1147                                                                           true);
1148 #endif
1149
1150                 if (lc == NULL)
1151                         return false; /* exception */
1152
1153                 /* move return value into `o' and cast it afterwards to a classinfo* */
1154
1155                 string = javastring_new_slash_to_dot(name);
1156
1157                 RT_TIMING_GET_TIME(time_prepare);
1158
1159                 o = vm_call_method(lc, (java_handle_t *) cl, string);
1160
1161                 RT_TIMING_GET_TIME(time_java);
1162
1163                 c = LLNI_classinfo_unwrap(o);
1164
1165                 if (c != NULL) {
1166                         /* Store this class in the loaded class cache. If another
1167                            class with the same (initloader,name) pair has been
1168                            stored earlier it will be returned by classcache_store
1169                            In this case classcache_store may not free the class
1170                            because it has already been exposed to Java code which
1171                            may have kept references to that class. */
1172
1173                     tmpc = classcache_store(cl, c, false);
1174
1175                         if (tmpc == NULL) {
1176                                 /* exception, free the loaded class */
1177                                 c->state &= ~CLASS_LOADING;
1178                                 class_free(c);
1179                         }
1180
1181                         c = tmpc;
1182                 }
1183
1184                 RT_TIMING_GET_TIME(time_cache);
1185
1186                 RT_TIMING_TIME_DIFF(time_lookup , time_prepare, RT_TIMING_LOAD_CL_PREPARE);
1187                 RT_TIMING_TIME_DIFF(time_prepare, time_java   , RT_TIMING_LOAD_CL_JAVA);
1188                 RT_TIMING_TIME_DIFF(time_java   , time_cache  , RT_TIMING_LOAD_CL_CACHE);
1189
1190                 /* SUN compatible -verbose:class output */
1191
1192                 if (opt_verboseclass && (c != NULL) && (c->classloader == cl)) {
1193                         printf("[Loaded ");
1194                         utf_display_printable_ascii_classname(name);
1195                         printf("]\n");
1196                 }
1197
1198 #if defined(ENABLE_JVMTI)
1199                 /* fire Class Load JVMTI event */
1200                 if (jvmti) jvmti_ClassLoadPrepare(false, c);
1201 #endif
1202
1203
1204                 return c;
1205         } 
1206
1207         c = load_class_bootstrap(name);
1208
1209         return c;
1210 }
1211
1212
1213 /* load_class_bootstrap ********************************************************
1214         
1215    Load the class with the given name using the bootstrap class loader.
1216
1217    IN:
1218        name.............the classname
1219
1220    RETURN VALUE:
1221        loaded classinfo, or
1222            NULL if an exception has been thrown
1223
1224    SYNCHRONIZATION:
1225        load_class_bootstrap is synchronized. It can be treated as an
1226            atomic operation.
1227
1228 *******************************************************************************/
1229
1230 classinfo *load_class_bootstrap(utf *name)
1231 {
1232         classbuffer *cb;
1233         classinfo   *c;
1234         classinfo   *r;
1235 #if defined(ENABLE_RT_TIMING)
1236         struct timespec time_start, time_lookup, time_array, time_suck, 
1237                                         time_load, time_cache;
1238 #endif
1239
1240         RT_TIMING_GET_TIME(time_start);
1241
1242         /* for debugging */
1243
1244         assert(name);
1245
1246         /* lookup if this class has already been loaded */
1247
1248         r = classcache_lookup(NULL, name);
1249
1250         if (r != NULL) {
1251                 RT_TIMING_GET_TIME(time_lookup);
1252                 RT_TIMING_TIME_DIFF(time_start,time_lookup,RT_TIMING_LOAD_BOOT_LOOKUP);
1253                 
1254                 return r;
1255         }
1256
1257         RT_TIMING_GET_TIME(time_lookup);
1258         RT_TIMING_TIME_DIFF(time_start,time_lookup,RT_TIMING_LOAD_BOOT_LOOKUP);
1259                 
1260         /* create the classinfo */
1261
1262         c = class_create_classinfo(name);
1263
1264         /* handle array classes */
1265
1266         if (name->text[0] == '[') {
1267                 c = load_newly_created_array(c, NULL);
1268
1269                 if (c == NULL)
1270                         return NULL;
1271
1272                 assert(c->state & CLASS_LOADED);
1273
1274                 RT_TIMING_GET_TIME(time_array);
1275                 RT_TIMING_TIME_DIFF(time_start,time_array,RT_TIMING_LOAD_BOOT_ARRAY);
1276                 
1277                 return c;
1278         }
1279
1280 #if defined(ENABLE_STATISTICS)
1281         /* measure time */
1282
1283         if (opt_getcompilingtime)
1284                 compilingtime_stop();
1285
1286         if (opt_getloadingtime)
1287                 loadingtime_start();
1288 #endif
1289
1290         /* load classdata, throw exception on error */
1291
1292         cb = suck_start(c);
1293
1294         if (cb == NULL) {
1295                 exceptions_throw_classnotfoundexception(name);
1296                 return NULL;
1297         }
1298
1299         RT_TIMING_GET_TIME(time_suck);
1300         
1301         /* load the class from the buffer */
1302
1303         r = load_class_from_classbuffer(cb);
1304
1305         RT_TIMING_GET_TIME(time_load);
1306         
1307         if (r == NULL) {
1308                 /* the class could not be loaded, free the classinfo struct */
1309
1310                 class_free(c);
1311         }
1312         else {
1313                 /* Store this class in the loaded class cache this step also
1314                    checks the loading constraints. If the class has been
1315                    loaded before, the earlier loaded class is returned. */
1316
1317                 classinfo *res = classcache_store(NULL, c, true);
1318
1319                 if (res == NULL) {
1320                         /* exception */
1321                         class_free(c);
1322                 }
1323                 else {
1324                         /* Add the package name to the boot packages. */
1325
1326                         package_add(c->packagename);
1327                 }
1328
1329                 r = res;
1330         }
1331
1332         RT_TIMING_GET_TIME(time_cache);
1333         
1334         /* SUN compatible -verbose:class output */
1335
1336         if (opt_verboseclass && r) {
1337                 printf("[Loaded ");
1338                 utf_display_printable_ascii_classname(name);
1339                 printf(" from %s]\n", cb->path);
1340         }
1341
1342         /* free memory */
1343
1344         suck_stop(cb);
1345
1346 #if defined(ENABLE_STATISTICS)
1347         /* measure time */
1348
1349         if (opt_getloadingtime)
1350                 loadingtime_stop();
1351
1352         if (opt_getcompilingtime)
1353                 compilingtime_start();
1354 #endif
1355
1356         RT_TIMING_TIME_DIFF(time_lookup, time_suck , RT_TIMING_LOAD_BOOT_SUCK);
1357         RT_TIMING_TIME_DIFF(time_suck  , time_load , RT_TIMING_LOAD_BOOT_LOAD);
1358         RT_TIMING_TIME_DIFF(time_load  , time_cache, RT_TIMING_LOAD_BOOT_CACHE);
1359         RT_TIMING_TIME_DIFF(time_lookup, time_cache, RT_TIMING_LOAD_BOOT_TOTAL);
1360
1361         return r;
1362 }
1363
1364
1365 /* load_class_from_classbuffer_intern ******************************************
1366         
1367    Loads a class from a classbuffer into a given classinfo structure.
1368    Super-classes are also loaded at this point and some verfication
1369    checks are done.
1370
1371    SYNCHRONIZATION:
1372        This function is NOT synchronized!
1373    
1374 *******************************************************************************/
1375
1376 static bool load_class_from_classbuffer_intern(classbuffer *cb)
1377 {
1378         classinfo          *c;
1379         classinfo          *tc;
1380         utf                *name;
1381         utf                *supername;
1382         utf               **interfacesnames;
1383         utf                *u;
1384         constant_classref  *cr;
1385         int16_t             index;
1386
1387         u4 i,j;
1388         u4 ma, mi;
1389         descriptor_pool *descpool;
1390 #if defined(ENABLE_STATISTICS)
1391         u4 classrefsize;
1392         u4 descsize;
1393 #endif
1394 #if defined(ENABLE_RT_TIMING)
1395         struct timespec time_start, time_checks, time_ndpool, time_cpool,
1396                                         time_setup, time_fields, time_methods, time_classrefs,
1397                                         time_descs,     time_setrefs, time_parsefds, time_parsemds,
1398                                         time_parsecpool, time_verify, time_attrs;
1399 #endif
1400
1401         RT_TIMING_GET_TIME(time_start);
1402
1403         /* Get the classbuffer's class. */
1404
1405         c = cb->clazz;
1406
1407         if (!suck_check_classbuffer_size(cb, 4 + 2 + 2))
1408                 return false;
1409
1410         /* check signature */
1411
1412         if (suck_u4(cb) != MAGIC) {
1413                 exceptions_throw_classformaterror(c, "Bad magic number");
1414                 return false;
1415         }
1416
1417         /* check version */
1418
1419         mi = suck_u2(cb);
1420         ma = suck_u2(cb);
1421
1422         if (!(ma < MAJOR_VERSION || (ma == MAJOR_VERSION && mi <= MINOR_VERSION))) {
1423                 exceptions_throw_unsupportedclassversionerror(c, ma, mi);
1424                 return false;
1425         }
1426
1427         RT_TIMING_GET_TIME(time_checks);
1428
1429         /* create a new descriptor pool */
1430
1431         descpool = descriptor_pool_new(c);
1432
1433         RT_TIMING_GET_TIME(time_ndpool);
1434
1435         /* load the constant pool */
1436
1437         if (!load_constantpool(cb, descpool))
1438                 return false;
1439
1440         RT_TIMING_GET_TIME(time_cpool);
1441
1442         /* ACC flags */
1443
1444         if (!suck_check_classbuffer_size(cb, 2))
1445                 return false;
1446
1447         /* We OR the flags here, as we set already some flags in
1448            class_create_classinfo. */
1449
1450         c->flags |= suck_u2(cb);
1451
1452         /* check ACC flags consistency */
1453
1454         if (c->flags & ACC_INTERFACE) {
1455                 if (!(c->flags & ACC_ABSTRACT)) {
1456                         /* We work around this because interfaces in JDK 1.1 are
1457                          * not declared abstract. */
1458
1459                         c->flags |= ACC_ABSTRACT;
1460                 }
1461
1462                 if (c->flags & ACC_FINAL) {
1463                         exceptions_throw_classformaterror(c,
1464                                                                                           "Illegal class modifiers: 0x%X",
1465                                                                                           c->flags);
1466                         return false;
1467                 }
1468
1469                 if (c->flags & ACC_SUPER) {
1470                         c->flags &= ~ACC_SUPER; /* kjc seems to set this on interfaces */
1471                 }
1472         }
1473
1474         if ((c->flags & (ACC_ABSTRACT | ACC_FINAL)) == (ACC_ABSTRACT | ACC_FINAL)) {
1475                 exceptions_throw_classformaterror(c,
1476                                                                                   "Illegal class modifiers: 0x%X",
1477                                                                                   c->flags);
1478                 return false;
1479         }
1480
1481         if (!suck_check_classbuffer_size(cb, 2 + 2))
1482                 return false;
1483
1484         /* This class. */
1485
1486         index = suck_u2(cb);
1487
1488         name = (utf *) class_getconstant(c, index, CONSTANT_Class);
1489
1490         if (name == NULL)
1491                 return false;
1492
1493         if (c->name == utf_not_named_yet) {
1494                 /* we finally have a name for this class */
1495                 c->name = name;
1496                 class_set_packagename(c);
1497         }
1498         else if (name != c->name) {
1499                 exceptions_throw_noclassdeffounderror_wrong_name(c, name);
1500                 return false;
1501         }
1502
1503         /* Retrieve superclass. */
1504
1505         c->super = NULL;
1506
1507         index = suck_u2(cb);
1508
1509         if (index == 0) {
1510                 supername = NULL;
1511
1512                 /* This is only allowed for java.lang.Object. */
1513
1514                 if (c->name != utf_java_lang_Object) {
1515                         exceptions_throw_classformaterror(c, "Bad superclass index");
1516                         return false;
1517                 }
1518         }
1519         else {
1520                 supername = (utf *) class_getconstant(c, index, CONSTANT_Class);
1521
1522                 if (supername == NULL)
1523                         return false;
1524
1525                 /* java.lang.Object may not have a super class. */
1526
1527                 if (c->name == utf_java_lang_Object) {
1528                         exceptions_throw_classformaterror(NULL, "java.lang.Object with superclass");
1529                         return false;
1530                 }
1531
1532                 /* Detect circularity. */
1533
1534                 if (supername == c->name) {
1535                         exceptions_throw_classcircularityerror(c);
1536                         return false;
1537                 }
1538
1539                 /* Interfaces must have java.lang.Object as super class. */
1540
1541                 if ((c->flags & ACC_INTERFACE) && (supername != utf_java_lang_Object)) {
1542                         exceptions_throw_classformaterror(c, "Interfaces must have java.lang.Object as superclass");
1543                         return false;
1544                 }
1545         }
1546
1547         /* Parse the super interfaces. */
1548
1549         if (!suck_check_classbuffer_size(cb, 2))
1550                 return false;
1551
1552         c->interfacescount = suck_u2(cb);
1553
1554         if (!suck_check_classbuffer_size(cb, 2 * c->interfacescount))
1555                 return false;
1556
1557         c->interfaces = MNEW(classinfo*, c->interfacescount);
1558
1559         /* Get the names of the super interfaces. */
1560
1561         interfacesnames = DMNEW(utf*, c->interfacescount);
1562
1563         for (i = 0; i < c->interfacescount; i++) {
1564                 index = suck_u2(cb);
1565
1566                 u = (utf *) class_getconstant(c, index, CONSTANT_Class);
1567
1568                 if (u == NULL)
1569                         return false;
1570
1571                 interfacesnames[i] = u;
1572         }
1573
1574         RT_TIMING_GET_TIME(time_setup);
1575
1576         /* Parse fields. */
1577
1578         if (!suck_check_classbuffer_size(cb, 2))
1579                 return false;
1580
1581         c->fieldscount = suck_u2(cb);
1582         c->fields      = MNEW(fieldinfo, c->fieldscount);
1583
1584         MZERO(c->fields, fieldinfo, c->fieldscount);
1585
1586         for (i = 0; i < c->fieldscount; i++) {
1587                 if (!field_load(cb, &(c->fields[i]), descpool))
1588                         return false;
1589         }
1590
1591         RT_TIMING_GET_TIME(time_fields);
1592
1593         /* Parse methods. */
1594
1595         if (!suck_check_classbuffer_size(cb, 2))
1596                 return false;
1597
1598         c->methodscount = suck_u2(cb);
1599         c->methods      = MNEW(methodinfo, c->methodscount);
1600
1601         MZERO(c->methods, methodinfo, c->methodscount);
1602         
1603         for (i = 0; i < c->methodscount; i++) {
1604                 if (!method_load(cb, &(c->methods[i]), descpool))
1605                         return false;
1606         }
1607
1608         RT_TIMING_GET_TIME(time_methods);
1609
1610         /* create the class reference table */
1611
1612         c->classrefs =
1613                 descriptor_pool_create_classrefs(descpool, &(c->classrefcount));
1614
1615         RT_TIMING_GET_TIME(time_classrefs);
1616
1617         /* allocate space for the parsed descriptors */
1618
1619         descriptor_pool_alloc_parsed_descriptors(descpool);
1620         c->parseddescs =
1621                 descriptor_pool_get_parsed_descriptors(descpool, &(c->parseddescsize));
1622
1623 #if defined(ENABLE_STATISTICS)
1624         if (opt_stat) {
1625                 descriptor_pool_get_sizes(descpool, &classrefsize, &descsize);
1626                 count_classref_len += classrefsize;
1627                 count_parsed_desc_len += descsize;
1628         }
1629 #endif
1630
1631         RT_TIMING_GET_TIME(time_descs);
1632
1633         /* put the classrefs in the constant pool */
1634
1635         for (i = 0; i < c->cpcount; i++) {
1636                 if (c->cptags[i] == CONSTANT_Class) {
1637                         utf *name = (utf *) c->cpinfos[i];
1638                         c->cpinfos[i] = descriptor_pool_lookup_classref(descpool, name);
1639                 }
1640         }
1641
1642         /* Resolve the super class. */
1643
1644         if (supername != NULL) {
1645                 cr = descriptor_pool_lookup_classref(descpool, supername);
1646
1647                 if (cr == NULL)
1648                         return false;
1649
1650                 /* XXX This should be done better. */
1651                 tc = resolve_classref_or_classinfo_eager(CLASSREF_OR_CLASSINFO(cr), false);
1652
1653                 if (tc == NULL) {
1654                         resolve_handle_pending_exception(true);
1655                         return false;
1656                 }
1657
1658                 /* Interfaces are not allowed as super classes. */
1659
1660                 if (tc->flags & ACC_INTERFACE) {
1661                         exceptions_throw_incompatibleclasschangeerror(c, "class %s has interface %s as super class");
1662                         return false;
1663                 }
1664
1665                 /* Don't allow extending final classes */
1666
1667                 if (tc->flags & ACC_FINAL) {
1668                         exceptions_throw_verifyerror(NULL,
1669                                                                                  "Cannot inherit from final class");
1670                         return false;
1671                 }
1672
1673                 /* Store the super class. */
1674
1675                 c->super = tc;
1676         }
1677
1678         /* Resolve the super interfaces. */
1679
1680         for (i = 0; i < c->interfacescount; i++) {
1681                 u  = interfacesnames[i];
1682                 cr = descriptor_pool_lookup_classref(descpool, u);
1683
1684                 if (cr == NULL)
1685                         return false;
1686
1687                 /* XXX This should be done better. */
1688                 tc = resolve_classref_or_classinfo_eager(CLASSREF_OR_CLASSINFO(cr), false);
1689
1690                 if (tc == NULL) {
1691                         resolve_handle_pending_exception(true);
1692                         return false;
1693                 }
1694
1695                 /* Detect circularity. */
1696
1697                 if (tc == c) {
1698                         exceptions_throw_classcircularityerror(c);
1699                         return false;
1700                 }
1701
1702                 if (!(tc->flags & ACC_INTERFACE)) {
1703                         exceptions_throw_incompatibleclasschangeerror(tc,
1704                                                                                                                   "Implementing class");
1705                         return false;
1706                 }
1707
1708                 /* Store the super interface. */
1709
1710                 c->interfaces[i] = tc;
1711         }
1712
1713         RT_TIMING_GET_TIME(time_setrefs);
1714
1715         /* Parse the field descriptors. */
1716
1717         for (i = 0; i < c->fieldscount; i++) {
1718                 c->fields[i].parseddesc =
1719                         descriptor_pool_parse_field_descriptor(descpool,
1720                                                                                                    c->fields[i].descriptor);
1721                 if (!c->fields[i].parseddesc)
1722                         return false;
1723         }
1724
1725         RT_TIMING_GET_TIME(time_parsefds);
1726
1727         /* parse method descriptors */
1728
1729         for (i = 0; i < c->methodscount; i++) {
1730                 methodinfo *m = &c->methods[i];
1731                 m->parseddesc =
1732                         descriptor_pool_parse_method_descriptor(descpool, m->descriptor,
1733                                                                                                         m->flags, class_get_self_classref(m->clazz));
1734                 if (!m->parseddesc)
1735                         return false;
1736
1737                 for (j = 0; j < m->rawexceptiontablelength; j++) {
1738                         if (!m->rawexceptiontable[j].catchtype.any)
1739                                 continue;
1740
1741                         if ((m->rawexceptiontable[j].catchtype.ref =
1742                                  descriptor_pool_lookup_classref(descpool,
1743                                                 (utf *) m->rawexceptiontable[j].catchtype.any)) == NULL)
1744                                 return false;
1745                 }
1746
1747                 for (j = 0; j < m->thrownexceptionscount; j++) {
1748                         if (!m->thrownexceptions[j].any)
1749                                 continue;
1750
1751                         if ((m->thrownexceptions[j].ref = descriptor_pool_lookup_classref(descpool,
1752                                                 (utf *) m->thrownexceptions[j].any)) == NULL)
1753                                 return false;
1754                 }
1755         }
1756
1757         RT_TIMING_GET_TIME(time_parsemds);
1758
1759         /* parse the loaded descriptors */
1760
1761         for (i = 0; i < c->cpcount; i++) {
1762                 constant_FMIref *fmi;
1763                 s4               index;
1764
1765                 switch (c->cptags[i]) {
1766                 case CONSTANT_Fieldref:
1767                         fmi = (constant_FMIref *) c->cpinfos[i];
1768                         fmi->parseddesc.fd =
1769                                 descriptor_pool_parse_field_descriptor(descpool,
1770                                                                                                            fmi->descriptor);
1771                         if (!fmi->parseddesc.fd)
1772                                 return false;
1773
1774                         index = fmi->p.index;
1775                         fmi->p.classref =
1776                                 (constant_classref *) class_getconstant(c, index,
1777                                                                                                                 CONSTANT_Class);
1778                         if (!fmi->p.classref)
1779                                 return false;
1780                         break;
1781                 case CONSTANT_Methodref:
1782                 case CONSTANT_InterfaceMethodref:
1783                         fmi = (constant_FMIref *) c->cpinfos[i];
1784                         index = fmi->p.index;
1785                         fmi->p.classref =
1786                                 (constant_classref *) class_getconstant(c, index,
1787                                                                                                                 CONSTANT_Class);
1788                         if (!fmi->p.classref)
1789                                 return false;
1790                         fmi->parseddesc.md =
1791                                 descriptor_pool_parse_method_descriptor(descpool,
1792                                                                                                                 fmi->descriptor,
1793                                                                                                                 ACC_UNDEF,
1794                                                                                                                 fmi->p.classref);
1795                         if (!fmi->parseddesc.md)
1796                                 return false;
1797                         break;
1798                 }
1799         }
1800
1801         RT_TIMING_GET_TIME(time_parsecpool);
1802
1803 #ifdef ENABLE_VERIFIER
1804         /* Check if all fields and methods can be uniquely
1805          * identified by (name,descriptor). */
1806
1807         if (opt_verify) {
1808                 /* We use a hash table here to avoid making the
1809                  * average case quadratic in # of methods, fields.
1810                  */
1811                 static int shift = 0;
1812                 u2 *hashtab;
1813                 u2 *next; /* for chaining colliding hash entries */
1814                 size_t len;
1815                 size_t hashlen;
1816                 u2 index;
1817                 u2 old;
1818
1819                 /* Allocate hashtable */
1820                 len = c->methodscount;
1821                 if (len < c->fieldscount) len = c->fieldscount;
1822                 hashlen = 5 * len;
1823                 hashtab = MNEW(u2,(hashlen + len));
1824                 next = hashtab + hashlen;
1825
1826                 /* Determine bitshift (to get good hash values) */
1827                 if (!shift) {
1828                         len = sizeof(utf);
1829                         while (len) {
1830                                 len >>= 1;
1831                                 shift++;
1832                         }
1833                 }
1834
1835                 /* Check fields */
1836                 memset(hashtab, 0, sizeof(u2) * (hashlen + len));
1837
1838                 for (i = 0; i < c->fieldscount; ++i) {
1839                         fieldinfo *fi = c->fields + i;
1840
1841                         /* It's ok if we lose bits here */
1842                         index = ((((size_t) fi->name) +
1843                                           ((size_t) fi->descriptor)) >> shift) % hashlen;
1844
1845                         if ((old = hashtab[index])) {
1846                                 old--;
1847                                 next[i] = old;
1848                                 do {
1849                                         if (c->fields[old].name == fi->name &&
1850                                                 c->fields[old].descriptor == fi->descriptor) {
1851                                                 exceptions_throw_classformaterror(c, "Repetitive field name/signature");
1852                                                 return false;
1853                                         }
1854                                 } while ((old = next[old]));
1855                         }
1856                         hashtab[index] = i + 1;
1857                 }
1858
1859                 /* Check methods */
1860                 memset(hashtab, 0, sizeof(u2) * (hashlen + hashlen/5));
1861
1862                 for (i = 0; i < c->methodscount; ++i) {
1863                         methodinfo *mi = c->methods + i;
1864
1865                         /* It's ok if we lose bits here */
1866                         index = ((((size_t) mi->name) +
1867                                           ((size_t) mi->descriptor)) >> shift) % hashlen;
1868
1869                         if ((old = hashtab[index])) {
1870                                 old--;
1871                                 next[i] = old;
1872                                 do {
1873                                         if (c->methods[old].name == mi->name &&
1874                                                 c->methods[old].descriptor == mi->descriptor) {
1875                                                 exceptions_throw_classformaterror(c, "Repetitive method name/signature");
1876                                                 return false;
1877                                         }
1878                                 } while ((old = next[old]));
1879                         }
1880                         hashtab[index] = i + 1;
1881                 }
1882
1883                 MFREE(hashtab, u2, (hashlen + len));
1884         }
1885 #endif /* ENABLE_VERIFIER */
1886
1887         RT_TIMING_GET_TIME(time_verify);
1888
1889 #if defined(ENABLE_STATISTICS)
1890         if (opt_stat) {
1891                 size_classinfo  += sizeof(classinfo*) * c->interfacescount;
1892                 size_fieldinfo  += sizeof(fieldinfo)  * c->fieldscount;
1893                 size_methodinfo += sizeof(methodinfo) * c->methodscount;
1894         }
1895 #endif
1896
1897         /* load attribute structures */
1898
1899         if (!class_load_attributes(cb))
1900                 return false;
1901
1902         /* Pre Java 1.5 version don't check this. This implementation is
1903            like Java 1.5 do it: for class file version 45.3 we don't check
1904            it, older versions are checked. */
1905
1906         if (((ma == 45) && (mi > 3)) || (ma > 45)) {
1907                 /* check if all data has been read */
1908                 s4 classdata_left = ((cb->data + cb->size) - cb->pos);
1909
1910                 if (classdata_left > 0) {
1911                         exceptions_throw_classformaterror(c, "Extra bytes at the end of class file");
1912                         return false;
1913                 }
1914         }
1915
1916         RT_TIMING_GET_TIME(time_attrs);
1917
1918         RT_TIMING_TIME_DIFF(time_start     , time_checks    , RT_TIMING_LOAD_CHECKS);
1919         RT_TIMING_TIME_DIFF(time_checks    , time_ndpool    , RT_TIMING_LOAD_NDPOOL);
1920         RT_TIMING_TIME_DIFF(time_ndpool    , time_cpool     , RT_TIMING_LOAD_CPOOL);
1921         RT_TIMING_TIME_DIFF(time_cpool     , time_setup     , RT_TIMING_LOAD_SETUP);
1922         RT_TIMING_TIME_DIFF(time_setup     , time_fields    , RT_TIMING_LOAD_FIELDS);
1923         RT_TIMING_TIME_DIFF(time_fields    , time_methods   , RT_TIMING_LOAD_METHODS);
1924         RT_TIMING_TIME_DIFF(time_methods   , time_classrefs , RT_TIMING_LOAD_CLASSREFS);
1925         RT_TIMING_TIME_DIFF(time_classrefs , time_descs     , RT_TIMING_LOAD_DESCS);
1926         RT_TIMING_TIME_DIFF(time_descs     , time_setrefs   , RT_TIMING_LOAD_SETREFS);
1927         RT_TIMING_TIME_DIFF(time_setrefs   , time_parsefds  , RT_TIMING_LOAD_PARSEFDS);
1928         RT_TIMING_TIME_DIFF(time_parsefds  , time_parsemds  , RT_TIMING_LOAD_PARSEMDS);
1929         RT_TIMING_TIME_DIFF(time_parsemds  , time_parsecpool, RT_TIMING_LOAD_PARSECP);
1930         RT_TIMING_TIME_DIFF(time_parsecpool, time_verify    , RT_TIMING_LOAD_VERIFY);
1931         RT_TIMING_TIME_DIFF(time_verify    , time_attrs     , RT_TIMING_LOAD_ATTRS);
1932         RT_TIMING_TIME_DIFF(time_start     , time_attrs     , RT_TIMING_LOAD_TOTAL);
1933
1934         return true;
1935 }
1936
1937
1938 /* load_class_from_classbuffer *************************************************
1939
1940    Convenience wrapper for load_class_from_classbuffer.
1941
1942    SYNCHRONIZATION:
1943        This function is NOT synchronized!
1944    
1945 *******************************************************************************/
1946
1947 classinfo *load_class_from_classbuffer(classbuffer *cb)
1948 {
1949         classinfo *c;
1950         bool       result;
1951         int32_t    dumpmarker;
1952
1953         /* Get the classbuffer's class. */
1954
1955         c = cb->clazz;
1956
1957         /* Check if the class is already loaded. */
1958
1959         if (c->state & CLASS_LOADED)
1960                 return c;
1961
1962 #if defined(ENABLE_STATISTICS)
1963         if (opt_stat)
1964                 count_class_loads++;
1965 #endif
1966
1967 #if !defined(NDEBUG)
1968         if (loadverbose)
1969                 log_message_class("Loading class: ", c);
1970 #endif
1971
1972         /* Mark start of dump memory area. */
1973
1974         DMARKER;
1975
1976         /* Class is currently loading. */
1977
1978         c->state |= CLASS_LOADING;
1979
1980         /* Parse the classbuffer. */
1981
1982         result = load_class_from_classbuffer_intern(cb);
1983
1984         /* Release dump area. */
1985
1986         DRELEASE;
1987
1988         /* An error occurred. */
1989
1990         if (result == false) {
1991                 /* Revert loading state. */
1992
1993                 c->state = (c->state & ~CLASS_LOADING);
1994
1995                 return NULL;
1996         }
1997
1998         /* Revert loading state and set loaded. */
1999
2000         c->state = (c->state & ~CLASS_LOADING) | CLASS_LOADED;
2001
2002 #if defined(ENABLE_JVMTI)
2003         /* fire Class Prepare JVMTI event */
2004
2005         if (jvmti)
2006                 jvmti_ClassLoadPrepare(true, c);
2007 #endif
2008
2009 #if !defined(NDEBUG)
2010         if (loadverbose)
2011                 log_message_class("Loading done class: ", c);
2012 #endif
2013
2014         return c;
2015 }
2016
2017
2018 /* load_newly_created_array ****************************************************
2019
2020    Load a newly created array class.
2021
2022         RETURN VALUE:
2023             c....................the array class C has been loaded
2024                 other classinfo......the array class was found in the class cache, 
2025                                      C has been freed
2026             NULL.................an exception has been thrown
2027
2028         Note:
2029                 This is an internal function. Do not use it unless you know exactly
2030                 what you are doing!
2031
2032                 Use one of the load_class_... functions for general array class loading.
2033
2034 *******************************************************************************/
2035
2036 classinfo *load_newly_created_array(classinfo *c, classloader_t *loader)
2037 {
2038         classinfo         *comp = NULL;
2039         methodinfo        *clone;
2040         methoddesc        *clonedesc;
2041         constant_classref *classrefs;
2042         char              *text;
2043         s4                 namelen;
2044         utf               *u;
2045
2046         text    = c->name->text;
2047         namelen = c->name->blength;
2048
2049         /* Check array class name */
2050
2051         if ((namelen < 2) || (text[0] != '[')) {
2052                 exceptions_throw_classnotfoundexception(c->name);
2053                 return NULL;
2054         }
2055
2056         /* Check the element type */
2057
2058         switch (text[1]) {
2059         case '[':
2060                 /* c is an array of arrays. We have to create the component class. */
2061
2062                 u = utf_new(text + 1, namelen - 1);
2063
2064                 comp = load_class_from_classloader(u, loader);
2065
2066                 if (comp == NULL)
2067                         return NULL;
2068
2069                 assert(comp->state & CLASS_LOADED);
2070
2071                 /* the array's flags are that of the component class */
2072                 c->flags = (comp->flags & ~ACC_INTERFACE) | ACC_FINAL | ACC_ABSTRACT;
2073                 c->classloader = comp->classloader;
2074                 break;
2075
2076         case 'L':
2077                 /* c is an array of objects. */
2078
2079                 /* check for cases like `[L;' or `[L[I;' or `[Ljava.lang.Object' */
2080                 if ((namelen < 4) || (text[2] == '[') || (text[namelen - 1] != ';')) {
2081                         exceptions_throw_classnotfoundexception(c->name);
2082                         return NULL;
2083                 }
2084
2085                 u = utf_new(text + 2, namelen - 3);
2086
2087                 if (!(comp = load_class_from_classloader(u, loader)))
2088                         return NULL;
2089
2090                 assert(comp->state & CLASS_LOADED);
2091
2092                 /* the array's flags are that of the component class */
2093                 c->flags = (comp->flags & ~ACC_INTERFACE) | ACC_FINAL | ACC_ABSTRACT;
2094                 c->classloader = comp->classloader;
2095                 break;
2096
2097         default:
2098                 /* c is an array of a primitive type */
2099
2100                 /* check for cases like `[II' and whether the character is a
2101                    valid primitive type */
2102
2103                 if ((namelen > 2) || (primitive_class_get_by_char(text[1]) == NULL)) {
2104                         exceptions_throw_classnotfoundexception(c->name);
2105                         return NULL;
2106                 }
2107
2108                 /* the accessibility of the array class is public (VM Spec 5.3.3) */
2109                 c->flags = ACC_PUBLIC | ACC_FINAL | ACC_ABSTRACT;
2110                 c->classloader = NULL;
2111         }
2112
2113         assert(class_java_lang_Object);
2114 #if defined(ENABLE_JAVASE)
2115         assert(class_java_lang_Cloneable);
2116         assert(class_java_io_Serializable);
2117 #endif
2118
2119         /* Setup the array class. */
2120
2121         c->super = class_java_lang_Object;
2122
2123 #if defined(ENABLE_JAVASE)
2124
2125         c->interfacescount = 2;
2126     c->interfaces      = MNEW(classinfo*, 2);
2127         c->interfaces[0]   = class_java_lang_Cloneable;
2128         c->interfaces[1]   = class_java_io_Serializable;
2129
2130 #elif defined(ENABLE_JAVAME_CLDC1_1)
2131
2132         c->interfacescount = 0;
2133         c->interfaces      = NULL;
2134
2135 #else
2136 # error unknow Java configuration
2137 #endif
2138
2139         c->methodscount = 1;
2140         c->methods      = MNEW(methodinfo, c->methodscount);
2141
2142         MZERO(c->methods, methodinfo, c->methodscount);
2143
2144         classrefs = MNEW(constant_classref, 2);
2145
2146         CLASSREF_INIT(classrefs[0], c, c->name);
2147         CLASSREF_INIT(classrefs[1], c, utf_java_lang_Object);
2148
2149         /* create descriptor for clone method */
2150         /* we need one paramslot which is reserved for the 'this' parameter */
2151         clonedesc = NEW(methoddesc);
2152         clonedesc->returntype.type = TYPE_ADR;
2153         clonedesc->returntype.classref = classrefs + 1;
2154         clonedesc->returntype.arraydim = 0;
2155         /* initialize params to "empty", add real params below in
2156            descriptor_params_from_paramtypes */
2157         clonedesc->paramcount = 0;
2158         clonedesc->paramslots = 0;
2159         clonedesc->paramtypes[0].classref = classrefs + 0;
2160         clonedesc->params = NULL;
2161
2162         /* create methodinfo */
2163
2164         clone = c->methods;
2165         MSET(clone, 0, methodinfo, 1);
2166
2167 #if defined(ENABLE_THREADS)
2168         lock_init_object_lock(&clone->header);
2169 #endif
2170
2171         /* ATTENTION: if you delete the ACC_NATIVE below, set
2172            clone->maxlocals=1 (interpreter related) */
2173
2174         clone->flags      = ACC_PUBLIC | ACC_NATIVE;
2175         clone->name       = utf_clone;
2176         clone->descriptor = utf_void__java_lang_Object;
2177         clone->parseddesc = clonedesc;
2178         clone->clazz      = c;
2179
2180         /* parse the descriptor to get the register allocation */
2181
2182         if (!descriptor_params_from_paramtypes(clonedesc, clone->flags))
2183                 return false;
2184
2185         clone->code = codegen_generate_stub_native(clone, BUILTIN_clone);
2186
2187         /* XXX: field: length? */
2188
2189         /* array classes are not loaded from class files */
2190
2191         c->state          |= CLASS_LOADED;
2192         c->parseddescs    = (u1 *) clonedesc;
2193         c->parseddescsize = sizeof(methodinfo);
2194         c->classrefs      = classrefs;
2195         c->classrefcount  = 1;
2196
2197         /* insert class into the loaded class cache */
2198         /* XXX free classinfo if NULL returned? */
2199
2200         return classcache_store(loader, c, true);
2201 }
2202
2203
2204 /* loader_close ****************************************************************
2205
2206    Frees all resources.
2207         
2208 *******************************************************************************/
2209
2210 void loader_close(void)
2211 {
2212         /* empty */
2213 }
2214
2215
2216 /*
2217  * These are local overrides for various environment variables in Emacs.
2218  * Please do not remove this and leave it at the end of the file, where
2219  * Emacs will automagically detect them.
2220  * ---------------------------------------------------------------------
2221  * Local variables:
2222  * mode: c
2223  * indent-tabs-mode: t
2224  * c-basic-offset: 4
2225  * tab-width: 4
2226  * End:
2227  * vim:noexpandtab:sw=4:ts=4:
2228  */