* src/vmcore/globals.cpp: New file.
[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.hpp"
47 #include "vm/primitive.hpp"
48 #include "vm/resolve.h"
49 #include "vm/stringlocal.h"
50 #include "vm/vm.hpp"
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/globals.hpp"
62 #include "vmcore/linker.h"
63 #include "vmcore/loader.h"
64 #include "vmcore/method.h"
65 #include "vmcore/options.h"
66 #include "vmcore/rt-timing.h"
67
68 #if defined(ENABLE_STATISTICS)
69 # include "vmcore/statistics.h"
70 #endif
71
72 #include "vmcore/suck.h"
73
74 #if defined(ENABLE_ZLIB)
75 # include "vmcore/zip.h"
76 #endif
77
78 #if defined(ENABLE_JVMTI)
79 # include "native/jvmti/cacaodbg.h"
80 #endif
81
82
83 /* global variables ***********************************************************/
84
85 static hashtable *hashtable_classloader;
86
87
88 /* loader_preinit **************************************************************
89
90    Initializes the classpath list and loads classes required for the
91    primitive table.
92
93    NOTE: Exceptions thrown during VM initialization are caught in the
94          exception functions themselves.
95
96 *******************************************************************************/
97  
98 void loader_preinit(void)
99 {
100 #if defined(ENABLE_THREADS)
101         list_classpath_entry *lce;
102 #endif
103
104         TRACESUBSYSTEMINITIALIZATION("loader_preinit");
105
106 #if defined(ENABLE_THREADS)
107         /* Initialize the monitor pointer for zip/jar file locking. */
108
109         for (lce = list_first(list_classpath_entries); lce != NULL;
110                  lce = list_next(list_classpath_entries, lce)) {
111                 if (lce->type == CLASSPATH_ARCHIVE)
112                         LOCK_INIT_OBJECT_LOCK(lce);
113         }
114 #endif
115
116         /* initialize classloader hashtable, 10 entries should be enough */
117
118         hashtable_classloader = NEW(hashtable);
119         hashtable_create(hashtable_classloader, 10);
120
121         /* Load the most basic classes. */
122
123         assert(VM_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_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_reflect_MagicAccessorImpl =
233                 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         LOCK_MONITOR_ENTER(hashtable_classloader->header);
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->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->ptr[slot];
321                 hashtable_classloader->ptr[slot] = cle;
322
323                 /* update number of entries */
324
325                 hashtable_classloader->entries++;
326         }
327
328
329         LOCK_MONITOR_EXIT(hashtable_classloader->header);
330
331 #if defined(ENABLE_HANDLES)
332         return cle;
333 #else
334         return cl;
335 #endif
336 }
337
338
339 /* loader_hashtable_classloader_find *******************************************
340
341    Find an entry in the classloader hashtable.
342
343 *******************************************************************************/
344
345 classloader_t *loader_hashtable_classloader_find(java_handle_t *cl)
346 {
347         hashtable_classloader_entry *cle;
348         u4   key;
349         u4   slot;
350
351         if (cl == NULL)
352                 return NULL;
353
354         LLNI_CRITICAL_START;
355
356         /* key for entry is the hashcode of the classloader;
357            aligned to 16-byte boundaries */
358
359         key  = heap_hashcode(LLNI_DIRECT(cl)) >> 4;
360         slot = key & (hashtable_classloader->size - 1);
361         cle  = hashtable_classloader->ptr[slot];
362
363         /* search hashchain for existing entry */
364
365         while (cle) {
366                 if (cle->object == LLNI_DIRECT(cl))
367                         break;
368
369                 cle = cle->hashlink;
370         }
371
372 #ifdef LOADER_DEBUG_CLASSLOADER
373         if (cle == NULL) {
374                 printf("CLASSLOADER: unable to find classloader entry for %p: ", cl);
375                 class_print(LLNI_vftbl_direct(cl)->class);
376                 printf("\n");
377                 fflush(stdout);
378         }
379 #endif
380
381         LLNI_CRITICAL_END;
382
383 #if defined(ENABLE_HANDLES)
384         return cle;
385 #else
386         return cl;
387 #endif
388 }
389
390
391 /* loader_load_all_classes *****************************************************
392
393    Loads all classes specified in the BOOTCLASSPATH.
394
395 *******************************************************************************/
396
397 void loader_load_all_classes(void)
398 {
399         list_classpath_entry    *lce;
400 #if defined(ENABLE_ZLIB)
401         hashtable               *ht;
402         s4                       slot;
403         hashtable_zipfile_entry *htzfe;
404         utf                     *u;
405 #endif
406
407         for (lce = list_first(list_classpath_entries); lce != NULL;
408                  lce = list_next(list_classpath_entries, lce)) {
409 #if defined(ENABLE_ZLIB)
410                 if (lce->type == CLASSPATH_ARCHIVE) {
411                         /* get the classes hashtable */
412
413                         ht = lce->htclasses;
414
415                         for (slot = 0; slot < ht->size; slot++) {
416                                 htzfe = (hashtable_zipfile_entry *) ht->ptr[slot];
417
418                                 for (; htzfe; htzfe = htzfe->hashlink) {
419                                         u = htzfe->filename;
420
421                                         /* skip all entries in META-INF and .properties,
422                        .png files */
423
424                                         if (!strncmp(u->text, "META-INF", strlen("META-INF")) ||
425                                                 strstr(u->text, ".properties") ||
426                                                 strstr(u->text, ".png"))
427                                                 continue;
428
429                                         /* load class from bootstrap classloader */
430
431                                         if (!load_class_bootstrap(u)) {
432                                                 fprintf(stderr, "Error loading: ");
433                                                 utf_fprint_printable_ascii_classname(stderr, u);
434                                                 fprintf(stderr, "\n");
435
436 #if !defined(NDEBUG)
437                                                 /* print out exception and cause */
438
439                                                 exceptions_print_current_exception();
440 #endif
441                                         }
442                                 }
443                         }
444
445                 } else {
446 #endif
447 #if defined(ENABLE_ZLIB)
448                 }
449 #endif
450         }
451 }
452
453
454 /* loader_skip_attribute_body **************************************************
455
456    Skips an attribute the attribute_name_index has already been read.
457         
458    attribute_info {
459        u2 attribute_name_index;
460        u4 attribute_length;
461        u1 info[attribute_length];
462    }
463
464 *******************************************************************************/
465
466 bool loader_skip_attribute_body(classbuffer *cb)
467 {
468         u4 attribute_length;
469
470         if (!suck_check_classbuffer_size(cb, 4))
471                 return false;
472
473         attribute_length = suck_u4(cb);
474
475         if (!suck_check_classbuffer_size(cb, attribute_length))
476                 return false;
477
478         suck_skip_nbytes(cb, attribute_length);
479
480         return true;
481 }
482
483
484 /* load_constantpool ***********************************************************
485
486    Loads the constantpool of a class, the entries are transformed into
487    a simpler format by resolving references (a detailed overview of
488    the compact structures can be found in global.h).
489
490 *******************************************************************************/
491
492 static bool load_constantpool(classbuffer *cb, descriptor_pool *descpool)
493 {
494
495         /* The following structures are used to save information which cannot be 
496            processed during the first pass. After the complete constantpool has 
497            been traversed the references can be resolved. 
498            (only in specific order)                                                */
499         
500         /* CONSTANT_Class entries */
501         typedef struct forward_class {
502                 struct forward_class *next;
503                 u2 thisindex;
504                 u2 name_index;
505         } forward_class;
506
507         /* CONSTANT_String */
508         typedef struct forward_string {
509                 struct forward_string *next;
510                 u2 thisindex;
511                 u2 string_index;
512         } forward_string;
513
514         /* CONSTANT_NameAndType */
515         typedef struct forward_nameandtype {
516                 struct forward_nameandtype *next;
517                 u2 thisindex;
518                 u2 name_index;
519                 u2 sig_index;
520         } forward_nameandtype;
521
522         /* CONSTANT_Fieldref, CONSTANT_Methodref or CONSTANT_InterfaceMethodref */
523         typedef struct forward_fieldmethint {
524                 struct forward_fieldmethint *next;
525                 u2 thisindex;
526                 u1 tag;
527                 u2 class_index;
528                 u2 nameandtype_index;
529         } forward_fieldmethint;
530
531
532         classinfo *c;
533         u4 idx;
534
535         forward_class *forward_classes = NULL;
536         forward_string *forward_strings = NULL;
537         forward_nameandtype *forward_nameandtypes = NULL;
538         forward_fieldmethint *forward_fieldmethints = NULL;
539
540         forward_class *nfc;
541         forward_string *nfs;
542         forward_nameandtype *nfn;
543         forward_fieldmethint *nff;
544
545         u4 cpcount;
546         u1 *cptags;
547         voidptr *cpinfos;
548
549         c = cb->clazz;
550
551         /* number of entries in the constant_pool table plus one */
552         if (!suck_check_classbuffer_size(cb, 2))
553                 return false;
554
555         cpcount = c->cpcount = suck_u2(cb);
556
557         /* allocate memory */
558         cptags  = c->cptags  = MNEW(u1, cpcount);
559         cpinfos = c->cpinfos = MNEW(voidptr, cpcount);
560
561         if (cpcount < 1) {
562                 exceptions_throw_classformaterror(c, "Illegal constant pool size");
563                 return false;
564         }
565         
566 #if defined(ENABLE_STATISTICS)
567         if (opt_stat)
568                 count_const_pool_len += (sizeof(u1) + sizeof(voidptr)) * cpcount;
569 #endif
570         
571         /* initialize constantpool */
572         for (idx = 0; idx < cpcount; idx++) {
573                 cptags[idx] = CONSTANT_UNUSED;
574                 cpinfos[idx] = NULL;
575         }
576
577                         
578         /******* first pass *******/
579         /* entries which cannot be resolved now are written into 
580            temporary structures and traversed again later        */
581                    
582         idx = 1;
583         while (idx < cpcount) {
584                 u4 t;
585
586                 /* get constant type */
587                 if (!suck_check_classbuffer_size(cb, 1))
588                         return false;
589
590                 t = suck_u1(cb);
591
592                 switch (t) {
593                 case CONSTANT_Class:
594                         nfc = DNEW(forward_class);
595
596                         nfc->next = forward_classes;
597                         forward_classes = nfc;
598
599                         nfc->thisindex = idx;
600                         /* reference to CONSTANT_NameAndType */
601                         if (!suck_check_classbuffer_size(cb, 2))
602                                 return false;
603
604                         nfc->name_index = suck_u2(cb);
605
606                         idx++;
607                         break;
608                         
609                 case CONSTANT_String:
610                         nfs = DNEW(forward_string);
611                                 
612                         nfs->next = forward_strings;
613                         forward_strings = nfs;
614                                 
615                         nfs->thisindex = idx;
616
617                         /* reference to CONSTANT_Utf8_info with string characters */
618                         if (!suck_check_classbuffer_size(cb, 2))
619                                 return false;
620
621                         nfs->string_index = suck_u2(cb);
622                                 
623                         idx++;
624                         break;
625
626                 case CONSTANT_NameAndType:
627                         nfn = DNEW(forward_nameandtype);
628                                 
629                         nfn->next = forward_nameandtypes;
630                         forward_nameandtypes = nfn;
631                                 
632                         nfn->thisindex = idx;
633
634                         if (!suck_check_classbuffer_size(cb, 2 + 2))
635                                 return false;
636
637                         /* reference to CONSTANT_Utf8_info containing simple name */
638                         nfn->name_index = suck_u2(cb);
639
640                         /* reference to CONSTANT_Utf8_info containing field or method
641                            descriptor */
642                         nfn->sig_index = suck_u2(cb);
643                                 
644                         idx++;
645                         break;
646
647                 case CONSTANT_Fieldref:
648                 case CONSTANT_Methodref:
649                 case CONSTANT_InterfaceMethodref:
650                         nff = DNEW(forward_fieldmethint);
651                         
652                         nff->next = forward_fieldmethints;
653                         forward_fieldmethints = nff;
654
655                         nff->thisindex = idx;
656                         /* constant type */
657                         nff->tag = t;
658
659                         if (!suck_check_classbuffer_size(cb, 2 + 2))
660                                 return false;
661
662                         /* class or interface type that contains the declaration of the
663                            field or method */
664                         nff->class_index = suck_u2(cb);
665
666                         /* name and descriptor of the field or method */
667                         nff->nameandtype_index = suck_u2(cb);
668
669                         idx++;
670                         break;
671                                 
672                 case CONSTANT_Integer: {
673                         constant_integer *ci = NEW(constant_integer);
674
675 #if defined(ENABLE_STATISTICS)
676                         if (opt_stat)
677                                 count_const_pool_len += sizeof(constant_integer);
678 #endif
679
680                         if (!suck_check_classbuffer_size(cb, 4))
681                                 return false;
682
683                         ci->value = suck_s4(cb);
684                         cptags[idx] = CONSTANT_Integer;
685                         cpinfos[idx] = ci;
686
687                         idx++;
688                         break;
689                 }
690                                 
691                 case CONSTANT_Float: {
692                         constant_float *cf = NEW(constant_float);
693
694 #if defined(ENABLE_STATISTICS)
695                         if (opt_stat)
696                                 count_const_pool_len += sizeof(constant_float);
697 #endif
698
699                         if (!suck_check_classbuffer_size(cb, 4))
700                                 return false;
701
702                         cf->value = suck_float(cb);
703                         cptags[idx] = CONSTANT_Float;
704                         cpinfos[idx] = cf;
705
706                         idx++;
707                         break;
708                 }
709                                 
710                 case CONSTANT_Long: {
711                         constant_long *cl = NEW(constant_long);
712                                         
713 #if defined(ENABLE_STATISTICS)
714                         if (opt_stat)
715                                 count_const_pool_len += sizeof(constant_long);
716 #endif
717
718                         if (!suck_check_classbuffer_size(cb, 8))
719                                 return false;
720
721                         cl->value = suck_s8(cb);
722                         cptags[idx] = CONSTANT_Long;
723                         cpinfos[idx] = cl;
724                         idx += 2;
725                         if (idx > cpcount) {
726                                 exceptions_throw_classformaterror(c, "Invalid constant pool entry");
727                                 return false;
728                         }
729                         break;
730                 }
731                         
732                 case CONSTANT_Double: {
733                         constant_double *cd = NEW(constant_double);
734                                 
735 #if defined(ENABLE_STATISTICS)
736                         if (opt_stat)
737                                 count_const_pool_len += sizeof(constant_double);
738 #endif
739
740                         if (!suck_check_classbuffer_size(cb, 8))
741                                 return false;
742
743                         cd->value = suck_double(cb);
744                         cptags[idx] = CONSTANT_Double;
745                         cpinfos[idx] = cd;
746                         idx += 2;
747                         if (idx > cpcount) {
748                                 exceptions_throw_classformaterror(c, "Invalid constant pool entry");
749                                 return false;
750                         }
751                         break;
752                 }
753                                 
754                 case CONSTANT_Utf8: { 
755                         u4 length;
756
757                         /* number of bytes in the bytes array (not string-length) */
758                         if (!suck_check_classbuffer_size(cb, 2))
759                                 return false;
760
761                         length = suck_u2(cb);
762                         cptags[idx] = CONSTANT_Utf8;
763
764                         /* validate the string */
765                         if (!suck_check_classbuffer_size(cb, length))
766                                 return false;
767
768 #ifdef ENABLE_VERIFIER
769                         if (opt_verify &&
770                                 !is_valid_utf((char *) cb->pos, (char *) (cb->pos + length))) 
771                         {
772                                 exceptions_throw_classformaterror(c, "Invalid UTF-8 string");
773                                 return false;
774                         }
775 #endif /* ENABLE_VERIFIER */
776                         /* insert utf-string into the utf-symboltable */
777                         cpinfos[idx] = utf_new((char *) cb->pos, length);
778
779                         /* skip bytes of the string (buffer size check above) */
780                         suck_skip_nbytes(cb, length);
781                         idx++;
782                         break;
783                 }
784                                                                                 
785                 default:
786                         exceptions_throw_classformaterror(c, "Illegal constant pool type");
787                         return false;
788                 }  /* end switch */
789         } /* end while */
790
791
792         /* resolve entries in temporary structures */
793
794         while (forward_classes) {
795                 utf *name =
796                         class_getconstant(c, forward_classes->name_index, CONSTANT_Utf8);
797                 if (!name)
798                         return false;
799
800 #ifdef ENABLE_VERIFIER
801                 if (opt_verify && !is_valid_name_utf(name)) {
802                         exceptions_throw_classformaterror(c, "Class reference with invalid name");
803                         return false;
804                 }
805 #endif /* ENABLE_VERIFIER */
806
807                 /* add all class references to the descriptor_pool */
808
809                 if (!descriptor_pool_add_class(descpool, name))
810                         return false;
811
812                 cptags[forward_classes->thisindex] = CONSTANT_Class;
813
814                 /* the classref is created later */
815                 cpinfos[forward_classes->thisindex] = name;
816
817                 nfc = forward_classes;
818                 forward_classes = forward_classes->next;
819         }
820
821         while (forward_strings) {
822                 utf *text =
823                         class_getconstant(c, forward_strings->string_index, CONSTANT_Utf8);
824                 if (!text)
825                         return false;
826
827                 /* resolve utf-string */
828                 cptags[forward_strings->thisindex] = CONSTANT_String;
829                 cpinfos[forward_strings->thisindex] = text;
830                 
831                 nfs = forward_strings;
832                 forward_strings = forward_strings->next;
833         }
834
835         while (forward_nameandtypes) {
836                 constant_nameandtype *cn = NEW(constant_nameandtype);   
837
838 #if defined(ENABLE_STATISTICS)
839                 if (opt_stat)
840                         count_const_pool_len += sizeof(constant_nameandtype);
841 #endif
842
843                 /* resolve simple name and descriptor */
844                 cn->name = class_getconstant(c,
845                                                                          forward_nameandtypes->name_index,
846                                                                          CONSTANT_Utf8);
847                 if (!cn->name)
848                         return false;
849
850                 cn->descriptor = class_getconstant(c,
851                                                                                    forward_nameandtypes->sig_index,
852                                                                                    CONSTANT_Utf8);
853                 if (!cn->descriptor)
854                         return false;
855
856 #ifdef ENABLE_VERIFIER
857                 if (opt_verify) {
858                         /* check name */
859                         if (!is_valid_name_utf(cn->name)) {
860                                 exceptions_throw_classformaterror(c,
861                                                                                                   "Illegal Field name \"%s\"",
862                                                                                                   cn->name->text);
863
864                                 return false;
865                         }
866
867                         /* disallow referencing <clinit> among others */
868                         if (cn->name->text[0] == '<' && cn->name != utf_init) {
869                                 exceptions_throw_classformaterror(c, "Illegal reference to special method");
870                                 return false;
871                         }
872                 }
873 #endif /* ENABLE_VERIFIER */
874
875                 cptags[forward_nameandtypes->thisindex] = CONSTANT_NameAndType;
876                 cpinfos[forward_nameandtypes->thisindex] = cn;
877
878                 nfn = forward_nameandtypes;
879                 forward_nameandtypes = forward_nameandtypes->next;
880         }
881
882         while (forward_fieldmethints) {
883                 constant_nameandtype *nat;
884                 constant_FMIref *fmi = NEW(constant_FMIref);
885
886 #if defined(ENABLE_STATISTICS)
887                 if (opt_stat)
888                         count_const_pool_len += sizeof(constant_FMIref);
889 #endif
890                 /* resolve simple name and descriptor */
891
892                 nat = class_getconstant(c,
893                                                                 forward_fieldmethints->nameandtype_index,
894                                                                 CONSTANT_NameAndType);
895                 if (!nat)
896                         return false;
897
898                 /* add all descriptors in {Field,Method}ref to the descriptor_pool */
899
900                 if (!descriptor_pool_add(descpool, nat->descriptor, NULL))
901                         return false;
902
903                 /* the classref is created later */
904
905                 fmi->p.index = forward_fieldmethints->class_index;
906                 fmi->name = nat->name;
907                 fmi->descriptor = nat->descriptor;
908
909                 cptags[forward_fieldmethints->thisindex] = forward_fieldmethints->tag;
910                 cpinfos[forward_fieldmethints->thisindex] = fmi;
911         
912                 nff = forward_fieldmethints;
913                 forward_fieldmethints = forward_fieldmethints->next;
914         }
915
916         /* everything was ok */
917
918         return true;
919 }
920
921
922 /* loader_load_attribute_signature *********************************************
923
924    Signature_attribute {
925        u2 attribute_name_index;
926            u4 atrribute_length;
927            u2 signature_index;
928    }
929
930 *******************************************************************************/
931
932 #if defined(ENABLE_JAVASE)
933 bool loader_load_attribute_signature(classbuffer *cb, utf **signature)
934 {
935         classinfo *c;
936         u4         attribute_length;
937         u2         signature_index;
938
939         /* get classinfo */
940
941         c = cb->clazz;
942
943         /* check remaining bytecode */
944
945         if (!suck_check_classbuffer_size(cb, 4 + 2))
946                 return false;
947
948         /* check attribute length */
949
950         attribute_length = suck_u4(cb);
951
952         if (attribute_length != 2) {
953                 exceptions_throw_classformaterror(c, "Wrong size for VALUE attribute");
954                 return false;
955         }
956
957         if (*signature != NULL) {
958                 exceptions_throw_classformaterror(c, "Multiple Signature attributes");
959                 return false;
960         }
961
962         /* get signature */
963
964         signature_index = suck_u2(cb);
965
966         if (!(*signature = class_getconstant(c, signature_index, CONSTANT_Utf8)))
967                 return false;
968
969         return true;
970 }
971 #endif /* defined(ENABLE_JAVASE) */
972
973
974 /* load_class_from_sysloader ***************************************************
975
976    Load the class with the given name using the system class loader
977
978    IN:
979        name.............the classname
980
981    RETURN VALUE:
982        the loaded class, or
983            NULL if an exception has been thrown
984
985 *******************************************************************************/
986
987 classinfo *load_class_from_sysloader(utf *name)
988 {
989         methodinfo    *m;
990         java_handle_t *clo;
991         classloader_t *cl;
992         classinfo     *c;
993
994         assert(class_java_lang_Object);
995         assert(class_java_lang_ClassLoader);
996         assert(class_java_lang_ClassLoader->state & CLASS_LINKED);
997         
998         m = class_resolveclassmethod(class_java_lang_ClassLoader,
999                                                                  utf_getSystemClassLoader,
1000                                                                  utf_void__java_lang_ClassLoader,
1001                                                                  class_java_lang_Object,
1002                                                                  false);
1003
1004         if (!m)
1005                 return false;
1006
1007         clo = vm_call_method(m, NULL);
1008
1009         if (!clo)
1010                 return false;
1011
1012         cl = loader_hashtable_classloader_add(clo);
1013
1014         c = load_class_from_classloader(name, cl);
1015
1016         return c;
1017 }
1018
1019
1020 /* load_class_from_classloader *************************************************
1021
1022    Load the class with the given name using the given user-defined class loader.
1023
1024    IN:
1025        name.............the classname
1026            cl...............user-defined class loader
1027            
1028    RETURN VALUE:
1029        the loaded class, or
1030            NULL if an exception has been thrown
1031
1032 *******************************************************************************/
1033
1034 classinfo *load_class_from_classloader(utf *name, classloader_t *cl)
1035 {
1036         java_handle_t *o;
1037         classinfo     *c;
1038         classinfo     *tmpc;
1039         java_handle_t *string;
1040 #if defined(ENABLE_RT_TIMING)
1041         struct timespec time_start, time_lookup, time_prepare, time_java, 
1042                                         time_cache;
1043 #endif
1044
1045         RT_TIMING_GET_TIME(time_start);
1046
1047         assert(name);
1048
1049         /* lookup if this class has already been loaded */
1050
1051         c = classcache_lookup(cl, name);
1052
1053         RT_TIMING_GET_TIME(time_lookup);
1054         RT_TIMING_TIME_DIFF(time_start,time_lookup,RT_TIMING_LOAD_CL_LOOKUP);
1055
1056         if (c != NULL)
1057                 return c;
1058
1059         /* if other class loader than bootstrap, call it */
1060
1061         if (cl != NULL) {
1062                 methodinfo *lc;
1063                 char       *text;
1064                 s4          namelen;
1065
1066                 text = name->text;
1067                 namelen = name->blength;
1068
1069                 /* handle array classes */
1070                 if (text[0] == '[') {
1071                         classinfo *comp;
1072                         utf       *u;
1073
1074                         switch (text[1]) {
1075                         case 'L':
1076                                 /* check for cases like `[L;' or `[L[I;' or `[Ljava.lang.Object' */
1077                                 if (namelen < 4 || text[2] == '[' || text[namelen - 1] != ';') {
1078                                         exceptions_throw_classnotfoundexception(name);
1079                                         return false;
1080                                 }
1081
1082                                 u = utf_new(text + 2, namelen - 3);
1083
1084                                 if (!(comp = load_class_from_classloader(u, cl)))
1085                                         return false;
1086
1087                                 /* create the array class */
1088
1089                                 c = class_array_of(comp, false);
1090
1091                                 tmpc = classcache_store(cl, c, true);
1092
1093                                 if (tmpc == NULL) {
1094                                         /* exception, free the loaded class */
1095                                         c->state &= ~CLASS_LOADING;
1096                                         class_free(c);
1097                                 }
1098
1099                                 return tmpc;
1100
1101                         case '[':
1102                                 /* load the component class */
1103
1104                                 u = utf_new(text + 1, namelen - 1);
1105
1106                                 if (!(comp = load_class_from_classloader(u, cl)))
1107                                         return false;
1108
1109                                 /* create the array class */
1110
1111                                 c = class_array_of(comp, false);
1112
1113                                 tmpc = classcache_store(cl, c, true);
1114
1115                                 if (tmpc == NULL) {
1116                                         /* exception, free the loaded class */
1117                                         c->state &= ~CLASS_LOADING;
1118                                         class_free(c);
1119                                 }
1120
1121                                 return tmpc;
1122
1123                         default:
1124                                 /* primitive array classes are loaded by the bootstrap loader */
1125
1126                                 c = load_class_bootstrap(name);
1127
1128                                 return c;
1129                         }
1130                 }
1131
1132                 LLNI_class_get(cl, c);
1133
1134 #if defined(WITH_JAVA_RUNTIME_LIBRARY_OPENJDK)
1135                 /* OpenJDK uses this internal function because it's
1136                    synchronized. */
1137
1138                 lc = class_resolveclassmethod(c,
1139                                                                           utf_loadClassInternal,
1140                                                                           utf_java_lang_String__java_lang_Class,
1141                                                                           NULL,
1142                                                                           true);
1143 #else
1144                 lc = class_resolveclassmethod(c,
1145                                                                           utf_loadClass,
1146                                                                           utf_java_lang_String__java_lang_Class,
1147                                                                           NULL,
1148                                                                           true);
1149 #endif
1150
1151                 if (lc == NULL)
1152                         return false; /* exception */
1153
1154                 /* move return value into `o' and cast it afterwards to a classinfo* */
1155
1156                 string = javastring_new_slash_to_dot(name);
1157
1158                 RT_TIMING_GET_TIME(time_prepare);
1159
1160                 o = vm_call_method(lc, (java_handle_t *) cl, string);
1161
1162                 RT_TIMING_GET_TIME(time_java);
1163
1164                 c = LLNI_classinfo_unwrap(o);
1165
1166                 if (c != NULL) {
1167                         /* Store this class in the loaded class cache. If another
1168                            class with the same (initloader,name) pair has been
1169                            stored earlier it will be returned by classcache_store
1170                            In this case classcache_store may not free the class
1171                            because it has already been exposed to Java code which
1172                            may have kept references to that class. */
1173
1174                     tmpc = classcache_store(cl, c, false);
1175
1176                         if (tmpc == NULL) {
1177                                 /* exception, free the loaded class */
1178                                 c->state &= ~CLASS_LOADING;
1179                                 class_free(c);
1180                         }
1181
1182                         c = tmpc;
1183                 }
1184
1185                 RT_TIMING_GET_TIME(time_cache);
1186
1187                 RT_TIMING_TIME_DIFF(time_lookup , time_prepare, RT_TIMING_LOAD_CL_PREPARE);
1188                 RT_TIMING_TIME_DIFF(time_prepare, time_java   , RT_TIMING_LOAD_CL_JAVA);
1189                 RT_TIMING_TIME_DIFF(time_java   , time_cache  , RT_TIMING_LOAD_CL_CACHE);
1190
1191                 /* SUN compatible -verbose:class output */
1192
1193                 if (opt_verboseclass && (c != NULL) && (c->classloader == cl)) {
1194                         printf("[Loaded ");
1195                         utf_display_printable_ascii_classname(name);
1196                         printf("]\n");
1197                 }
1198
1199 #if defined(ENABLE_JVMTI)
1200                 /* fire Class Load JVMTI event */
1201                 if (jvmti) jvmti_ClassLoadPrepare(false, c);
1202 #endif
1203
1204
1205                 return c;
1206         } 
1207
1208         c = load_class_bootstrap(name);
1209
1210         return c;
1211 }
1212
1213
1214 /* load_class_bootstrap ********************************************************
1215         
1216    Load the class with the given name using the bootstrap class loader.
1217
1218    IN:
1219        name.............the classname
1220
1221    RETURN VALUE:
1222        loaded classinfo, or
1223            NULL if an exception has been thrown
1224
1225    SYNCHRONIZATION:
1226        load_class_bootstrap is synchronized. It can be treated as an
1227            atomic operation.
1228
1229 *******************************************************************************/
1230
1231 classinfo *load_class_bootstrap(utf *name)
1232 {
1233         classbuffer *cb;
1234         classinfo   *c;
1235         classinfo   *r;
1236 #if defined(ENABLE_RT_TIMING)
1237         struct timespec time_start, time_lookup, time_array, time_suck, 
1238                                         time_load, time_cache;
1239 #endif
1240
1241         RT_TIMING_GET_TIME(time_start);
1242
1243         /* for debugging */
1244
1245         assert(name);
1246
1247         /* lookup if this class has already been loaded */
1248
1249         r = classcache_lookup(NULL, name);
1250
1251         if (r != NULL) {
1252                 RT_TIMING_GET_TIME(time_lookup);
1253                 RT_TIMING_TIME_DIFF(time_start,time_lookup,RT_TIMING_LOAD_BOOT_LOOKUP);
1254                 
1255                 return r;
1256         }
1257
1258         RT_TIMING_GET_TIME(time_lookup);
1259         RT_TIMING_TIME_DIFF(time_start,time_lookup,RT_TIMING_LOAD_BOOT_LOOKUP);
1260                 
1261         /* create the classinfo */
1262
1263         c = class_create_classinfo(name);
1264
1265         /* handle array classes */
1266
1267         if (name->text[0] == '[') {
1268                 c = load_newly_created_array(c, NULL);
1269
1270                 if (c == NULL)
1271                         return NULL;
1272
1273                 assert(c->state & CLASS_LOADED);
1274
1275                 RT_TIMING_GET_TIME(time_array);
1276                 RT_TIMING_TIME_DIFF(time_start,time_array,RT_TIMING_LOAD_BOOT_ARRAY);
1277                 
1278                 return c;
1279         }
1280
1281 #if defined(ENABLE_STATISTICS)
1282         /* measure time */
1283
1284         if (opt_getcompilingtime)
1285                 compilingtime_stop();
1286
1287         if (opt_getloadingtime)
1288                 loadingtime_start();
1289 #endif
1290
1291         /* load classdata, throw exception on error */
1292
1293         cb = suck_start(c);
1294
1295         if (cb == NULL) {
1296                 exceptions_throw_classnotfoundexception(name);
1297                 return NULL;
1298         }
1299
1300         RT_TIMING_GET_TIME(time_suck);
1301         
1302         /* load the class from the buffer */
1303
1304         r = load_class_from_classbuffer(cb);
1305
1306         RT_TIMING_GET_TIME(time_load);
1307         
1308         if (r == NULL) {
1309                 /* the class could not be loaded, free the classinfo struct */
1310
1311                 class_free(c);
1312         }
1313         else {
1314                 /* Store this class in the loaded class cache this step also
1315                    checks the loading constraints. If the class has been
1316                    loaded before, the earlier loaded class is returned. */
1317
1318                 classinfo *res = classcache_store(NULL, c, true);
1319
1320                 if (res == NULL) {
1321                         /* exception */
1322                         class_free(c);
1323                 }
1324                 else {
1325                         /* Add the package name to the boot packages. */
1326
1327                         Package_add(c->packagename);
1328                 }
1329
1330                 r = res;
1331         }
1332
1333         RT_TIMING_GET_TIME(time_cache);
1334         
1335         /* SUN compatible -verbose:class output */
1336
1337         if (opt_verboseclass && r) {
1338                 printf("[Loaded ");
1339                 utf_display_printable_ascii_classname(name);
1340                 printf(" from %s]\n", cb->path);
1341         }
1342
1343         /* free memory */
1344
1345         suck_stop(cb);
1346
1347 #if defined(ENABLE_STATISTICS)
1348         /* measure time */
1349
1350         if (opt_getloadingtime)
1351                 loadingtime_stop();
1352
1353         if (opt_getcompilingtime)
1354                 compilingtime_start();
1355 #endif
1356
1357         RT_TIMING_TIME_DIFF(time_lookup, time_suck , RT_TIMING_LOAD_BOOT_SUCK);
1358         RT_TIMING_TIME_DIFF(time_suck  , time_load , RT_TIMING_LOAD_BOOT_LOAD);
1359         RT_TIMING_TIME_DIFF(time_load  , time_cache, RT_TIMING_LOAD_BOOT_CACHE);
1360         RT_TIMING_TIME_DIFF(time_lookup, time_cache, RT_TIMING_LOAD_BOOT_TOTAL);
1361
1362         return r;
1363 }
1364
1365
1366 /* load_class_from_classbuffer_intern ******************************************
1367         
1368    Loads a class from a classbuffer into a given classinfo structure.
1369    Super-classes are also loaded at this point and some verfication
1370    checks are done.
1371
1372    SYNCHRONIZATION:
1373        This function is NOT synchronized!
1374    
1375 *******************************************************************************/
1376
1377 static bool load_class_from_classbuffer_intern(classbuffer *cb)
1378 {
1379         classinfo          *c;
1380         classinfo          *tc;
1381         utf                *name;
1382         utf                *supername;
1383         utf               **interfacesnames;
1384         utf                *u;
1385         constant_classref  *cr;
1386         int16_t             index;
1387
1388         u4 i,j;
1389         u4 ma, mi;
1390         descriptor_pool *descpool;
1391 #if defined(ENABLE_STATISTICS)
1392         u4 classrefsize;
1393         u4 descsize;
1394 #endif
1395 #if defined(ENABLE_RT_TIMING)
1396         struct timespec time_start, time_checks, time_ndpool, time_cpool,
1397                                         time_setup, time_fields, time_methods, time_classrefs,
1398                                         time_descs,     time_setrefs, time_parsefds, time_parsemds,
1399                                         time_parsecpool, time_verify, time_attrs;
1400 #endif
1401
1402         RT_TIMING_GET_TIME(time_start);
1403
1404         /* Get the classbuffer's class. */
1405
1406         c = cb->clazz;
1407
1408         if (!suck_check_classbuffer_size(cb, 4 + 2 + 2))
1409                 return false;
1410
1411         /* check signature */
1412
1413         if (suck_u4(cb) != MAGIC) {
1414                 exceptions_throw_classformaterror(c, "Bad magic number");
1415                 return false;
1416         }
1417
1418         /* check version */
1419
1420         mi = suck_u2(cb);
1421         ma = suck_u2(cb);
1422
1423         if (!(ma < MAJOR_VERSION || (ma == MAJOR_VERSION && mi <= MINOR_VERSION))) {
1424                 exceptions_throw_unsupportedclassversionerror(c, ma, mi);
1425                 return false;
1426         }
1427
1428         RT_TIMING_GET_TIME(time_checks);
1429
1430         /* create a new descriptor pool */
1431
1432         descpool = descriptor_pool_new(c);
1433
1434         RT_TIMING_GET_TIME(time_ndpool);
1435
1436         /* load the constant pool */
1437
1438         if (!load_constantpool(cb, descpool))
1439                 return false;
1440
1441         RT_TIMING_GET_TIME(time_cpool);
1442
1443         /* ACC flags */
1444
1445         if (!suck_check_classbuffer_size(cb, 2))
1446                 return false;
1447
1448         /* We OR the flags here, as we set already some flags in
1449            class_create_classinfo. */
1450
1451         c->flags |= suck_u2(cb);
1452
1453         /* check ACC flags consistency */
1454
1455         if (c->flags & ACC_INTERFACE) {
1456                 if (!(c->flags & ACC_ABSTRACT)) {
1457                         /* We work around this because interfaces in JDK 1.1 are
1458                          * not declared abstract. */
1459
1460                         c->flags |= ACC_ABSTRACT;
1461                 }
1462
1463                 if (c->flags & ACC_FINAL) {
1464                         exceptions_throw_classformaterror(c,
1465                                                                                           "Illegal class modifiers: 0x%X",
1466                                                                                           c->flags);
1467                         return false;
1468                 }
1469
1470                 if (c->flags & ACC_SUPER) {
1471                         c->flags &= ~ACC_SUPER; /* kjc seems to set this on interfaces */
1472                 }
1473         }
1474
1475         if ((c->flags & (ACC_ABSTRACT | ACC_FINAL)) == (ACC_ABSTRACT | ACC_FINAL)) {
1476                 exceptions_throw_classformaterror(c,
1477                                                                                   "Illegal class modifiers: 0x%X",
1478                                                                                   c->flags);
1479                 return false;
1480         }
1481
1482         if (!suck_check_classbuffer_size(cb, 2 + 2))
1483                 return false;
1484
1485         /* This class. */
1486
1487         index = suck_u2(cb);
1488
1489         name = (utf *) class_getconstant(c, index, CONSTANT_Class);
1490
1491         if (name == NULL)
1492                 return false;
1493
1494         if (c->name == utf_not_named_yet) {
1495                 /* we finally have a name for this class */
1496                 c->name = name;
1497                 class_set_packagename(c);
1498         }
1499         else if (name != c->name) {
1500                 exceptions_throw_noclassdeffounderror_wrong_name(c, name);
1501                 return false;
1502         }
1503
1504         /* Retrieve superclass. */
1505
1506         c->super = NULL;
1507
1508         index = suck_u2(cb);
1509
1510         if (index == 0) {
1511                 supername = NULL;
1512
1513                 /* This is only allowed for java.lang.Object. */
1514
1515                 if (c->name != utf_java_lang_Object) {
1516                         exceptions_throw_classformaterror(c, "Bad superclass index");
1517                         return false;
1518                 }
1519         }
1520         else {
1521                 supername = (utf *) class_getconstant(c, index, CONSTANT_Class);
1522
1523                 if (supername == NULL)
1524                         return false;
1525
1526                 /* java.lang.Object may not have a super class. */
1527
1528                 if (c->name == utf_java_lang_Object) {
1529                         exceptions_throw_classformaterror(NULL, "java.lang.Object with superclass");
1530                         return false;
1531                 }
1532
1533                 /* Detect circularity. */
1534
1535                 if (supername == c->name) {
1536                         exceptions_throw_classcircularityerror(c);
1537                         return false;
1538                 }
1539
1540                 /* Interfaces must have java.lang.Object as super class. */
1541
1542                 if ((c->flags & ACC_INTERFACE) && (supername != utf_java_lang_Object)) {
1543                         exceptions_throw_classformaterror(c, "Interfaces must have java.lang.Object as superclass");
1544                         return false;
1545                 }
1546         }
1547
1548         /* Parse the super interfaces. */
1549
1550         if (!suck_check_classbuffer_size(cb, 2))
1551                 return false;
1552
1553         c->interfacescount = suck_u2(cb);
1554
1555         if (!suck_check_classbuffer_size(cb, 2 * c->interfacescount))
1556                 return false;
1557
1558         c->interfaces = MNEW(classinfo*, c->interfacescount);
1559
1560         /* Get the names of the super interfaces. */
1561
1562         interfacesnames = DMNEW(utf*, c->interfacescount);
1563
1564         for (i = 0; i < c->interfacescount; i++) {
1565                 index = suck_u2(cb);
1566
1567                 u = (utf *) class_getconstant(c, index, CONSTANT_Class);
1568
1569                 if (u == NULL)
1570                         return false;
1571
1572                 interfacesnames[i] = u;
1573         }
1574
1575         RT_TIMING_GET_TIME(time_setup);
1576
1577         /* Parse fields. */
1578
1579         if (!suck_check_classbuffer_size(cb, 2))
1580                 return false;
1581
1582         c->fieldscount = suck_u2(cb);
1583         c->fields      = MNEW(fieldinfo, c->fieldscount);
1584
1585         MZERO(c->fields, fieldinfo, c->fieldscount);
1586
1587         for (i = 0; i < c->fieldscount; i++) {
1588                 if (!field_load(cb, &(c->fields[i]), descpool))
1589                         return false;
1590         }
1591
1592         RT_TIMING_GET_TIME(time_fields);
1593
1594         /* Parse methods. */
1595
1596         if (!suck_check_classbuffer_size(cb, 2))
1597                 return false;
1598
1599         c->methodscount = suck_u2(cb);
1600         c->methods      = MNEW(methodinfo, c->methodscount);
1601
1602         MZERO(c->methods, methodinfo, c->methodscount);
1603         
1604         for (i = 0; i < c->methodscount; i++) {
1605                 if (!method_load(cb, &(c->methods[i]), descpool))
1606                         return false;
1607         }
1608
1609         RT_TIMING_GET_TIME(time_methods);
1610
1611         /* create the class reference table */
1612
1613         c->classrefs =
1614                 descriptor_pool_create_classrefs(descpool, &(c->classrefcount));
1615
1616         RT_TIMING_GET_TIME(time_classrefs);
1617
1618         /* allocate space for the parsed descriptors */
1619
1620         descriptor_pool_alloc_parsed_descriptors(descpool);
1621         c->parseddescs =
1622                 descriptor_pool_get_parsed_descriptors(descpool, &(c->parseddescsize));
1623
1624 #if defined(ENABLE_STATISTICS)
1625         if (opt_stat) {
1626                 descriptor_pool_get_sizes(descpool, &classrefsize, &descsize);
1627                 count_classref_len += classrefsize;
1628                 count_parsed_desc_len += descsize;
1629         }
1630 #endif
1631
1632         RT_TIMING_GET_TIME(time_descs);
1633
1634         /* put the classrefs in the constant pool */
1635
1636         for (i = 0; i < c->cpcount; i++) {
1637                 if (c->cptags[i] == CONSTANT_Class) {
1638                         utf *name = (utf *) c->cpinfos[i];
1639                         c->cpinfos[i] = descriptor_pool_lookup_classref(descpool, name);
1640                 }
1641         }
1642
1643         /* Resolve the super class. */
1644
1645         if (supername != NULL) {
1646                 cr = descriptor_pool_lookup_classref(descpool, supername);
1647
1648                 if (cr == NULL)
1649                         return false;
1650
1651                 /* XXX This should be done better. */
1652                 tc = resolve_classref_or_classinfo_eager(CLASSREF_OR_CLASSINFO(cr), false);
1653
1654                 if (tc == NULL) {
1655                         resolve_handle_pending_exception(true);
1656                         return false;
1657                 }
1658
1659                 /* Interfaces are not allowed as super classes. */
1660
1661                 if (tc->flags & ACC_INTERFACE) {
1662                         exceptions_throw_incompatibleclasschangeerror(c, "class %s has interface %s as super class");
1663                         return false;
1664                 }
1665
1666                 /* Don't allow extending final classes */
1667
1668                 if (tc->flags & ACC_FINAL) {
1669                         exceptions_throw_verifyerror(NULL,
1670                                                                                  "Cannot inherit from final class");
1671                         return false;
1672                 }
1673
1674                 /* Store the super class. */
1675
1676                 c->super = tc;
1677         }
1678
1679         /* Resolve the super interfaces. */
1680
1681         for (i = 0; i < c->interfacescount; i++) {
1682                 u  = interfacesnames[i];
1683                 cr = descriptor_pool_lookup_classref(descpool, u);
1684
1685                 if (cr == NULL)
1686                         return false;
1687
1688                 /* XXX This should be done better. */
1689                 tc = resolve_classref_or_classinfo_eager(CLASSREF_OR_CLASSINFO(cr), false);
1690
1691                 if (tc == NULL) {
1692                         resolve_handle_pending_exception(true);
1693                         return false;
1694                 }
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->clazz));
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->clazz;
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_t *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_get_class_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->clazz      = 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  */