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