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