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