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