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